(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function t(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=t(i);fetch(i.href,a)}})();const un={},c1=Object.freeze(Object.defineProperty({__proto__:null,default:un},Symbol.toStringTag,{value:"Module"})),d1="3.0.0-alpha.0",Ql=typeof self<"u",h1=Ql&&self.constructor.name==="DedicatedWorkerGlobalScope",z_=Ql&&"caches"in self,p1=typeof navigator<"u"&&"gpu"in navigator,N_=typeof process<"u",f1=N_&&process?.release?.name==="node",$l=!F_(un),U_=!F_(un),pa=Object.freeze({IS_BROWSER_ENV:Ql,IS_WEBWORKER_ENV:h1,IS_WEB_CACHE_AVAILABLE:z_,IS_WEBGPU_AVAILABLE:p1,IS_PROCESS_AVAILABLE:N_,IS_NODE_ENV:f1,IS_FS_AVAILABLE:$l,IS_PATH_AVAILABLE:U_}),cd=$l&&U_,B_=cd?un.dirname(un.dirname(un.fileURLToPath(import.meta.url))):"./",m1=cd?un.join(B_,"/.cache/"):null,Lh="/models/",g1=cd?un.join(B_,Lh):Lh,er={version:d1,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ql,localModelPath:g1,useFS:$l,useBrowserCache:z_,useFSCache:$l,cacheDir:m1,useCustomCache:!1,customCache:null};function F_(n){return Object.keys(n).length===0}const Nn=class{constructor(){let n=function(...e){return n._call(...e)};return Object.setPrototypeOf(n,new.target.prototype)}_call(...n){throw Error("Must implement _call method in subclass")}};function Za(n,e){n&&n(e)}function _1(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[t,e]))}function G_(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y1(n){return Number.isInteger(n)||typeof n=="bigint"}function zh(n){const e=[];let t=n;for(;Array.isArray(t);)e.push(t.length),t=t[0];return e}function Cn(...n){return Array.prototype.concat.apply([],n)}function v1(...n){return n.reduce((e,t)=>e.flatMap(r=>t.map(i=>[r,i])))}function Rl(n,e){return Math.abs((n+e)%(2*e)-e)}function oa(n,e){return Object.assign({},...e.map(t=>{if(n[t]!==void 0)return{[t]:n[t]}}))}var Eu={};class Jl{_CONTENT_TYPE_MAP={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=un.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=un.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let r=this;this.body=new ReadableStream({start(i){r.arrayBuffer().then(a=>{i.enqueue(new Uint8Array(a)),i.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new Jl(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await un.promises.readFile(this.filePath)).buffer}async blob(){const e=await un.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await un.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function Nc(n,e=null,t=null){let r;try{r=new URL(n)}catch{return!1}return!(e&&!e.includes(r.protocol)||t&&!t.includes(r.hostname))}async function Il(n){if(er.useFS&&!Nc(n,["http:","https:","blob:"]))return new Jl(n);if(typeof process<"u"&&process?.release?.name==="node"){const e=!!Eu?.TESTING_REMOTELY,t=er.version,r=new Headers;if(r.set("User-Agent",`transformers.js/${t}; is_ci/${e};`),Nc(n,["http:","https:"],["huggingface.co","hf.co"])){const a=Eu?.HF_TOKEN??Eu?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}return fetch(n,{headers:r})}else return fetch(n)}const w1={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function b1(n,e,t){if(!t)return null;const r=w1[n]??`Error (${n}) occurred while trying to load file`;throw Error(`${r}: "${e}".`)}class Nh{constructor(e){this.path=e}async match(e){let t=un.join(this.path,e),r=new Jl(t);if(r.exists)return r}async put(e,t){const r=Buffer.from(await t.arrayBuffer());let i=un.join(this.path,e);try{await un.promises.mkdir(un.dirname(i),{recursive:!0}),await un.promises.writeFile(i,r)}catch(a){console.warn("An error occurred while writing the file to cache:",a)}}}async function x1(n,...e){for(let t of e)try{let r=await n.match(t);if(r)return r}catch{continue}}async function vl(n,e,t=!0,r={}){if(!er.allowLocalModels&&r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");Za(r.progress_callback,{status:"initiate",name:n,file:e});let i;if(!i&&er.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{i=await caches.open("transformers-cache")}catch(_){console.warn("An error occurred while opening the browser cache:",_)}}if(!i&&er.useFSCache&&(i=new Nh(r.cache_dir??er.cacheDir)),!i&&er.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const a=r.revision??"main";let s=Do(n,e),o=Do(er.localModelPath,s),l=Do(er.remoteHost,er.remotePathTemplate.replaceAll("{model}",n).replaceAll("{revision}",encodeURIComponent(a)),e),u=a==="main"?s:Do(n,a,e),c,h=i instanceof Nh?u:l,p=!1,d;i&&(d=await x1(i,o,h));const m=d!==void 0;if(d===void 0){if(er.allowLocalModels)if(Nc(s,["http:","https:"])){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else try{d=await Il(o),c=o}catch(w){console.warn(`Unable to load from local path "${o}": "${w}"`)}if(d===void 0||d.status===404){if(r.local_files_only||!er.allowRemoteModels){if(t)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${o}".`);return null}if(d=await Il(l),d.status!==200)return b1(d.status,l,t);c=h}p=i&&typeof Response<"u"&&d instanceof Response&&d.status===200}Za(r.progress_callback,{status:"download",name:n,file:e});const y={status:"progress",name:n,file:e};let g;return r.progress_callback?m&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(g=new Uint8Array(await d.arrayBuffer()),Za(r.progress_callback,{...y,progress:100,loaded:g.length,total:g.length})):g=await S1(d,_=>{Za(r.progress_callback,{...y,..._})}):g=new Uint8Array(await d.arrayBuffer()),p&&c&&await i.match(c)===void 0&&await i.put(c,new Response(g,{headers:d.headers})).catch(_=>{console.warn(`Unable to add response to browser cache: ${_}.`)}),Za(r.progress_callback,{status:"done",name:n,file:e}),g}async function Ii(n,e,t=!0,r={}){let i=await vl(n,e,t,r);if(i===null)return{};let s=new TextDecoder("utf-8").decode(i);return JSON.parse(s)}async function S1(n,e){const t=n.headers.get("Content-Length");t===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(t??"0"),i=new Uint8Array(r),a=0;const s=n.body.getReader();async function o(){const{done:l,value:u}=await s.read();if(l)return;let c=a+u.length;if(c>r){r=c;let p=new Uint8Array(r);p.set(i),i=p}i.set(u,a),a=c;const h=a/r*100;return e({progress:h,loaded:a,total:r}),o()}return await o(),i}function Do(...n){return n=n.map((e,t)=>(t&&(e=e.replace(new RegExp("^/"),"")),t!==n.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),n.join("/")}function E1(n,[e,t,r],[i,a],s="bilinear",o=!1){const l=a/r,u=i/t,c=new n.constructor(i*a*e),h=t*r,p=i*a;for(let d=0;d=0;--o)i[o]=l,r[o]=e[t[o]],l*=r[o];const a=t.map((o,l)=>i[t.indexOf(l)]),s=new n.constructor(n.length);for(let o=0;o=0;--u)l+=c%e[u]*a[u],c=Math.floor(c/e[u]);s[l]=n[o]}return[s,r]}function zn(n){const e=wr(n)[0],t=n.map(a=>Math.exp(a-e)),r=t.reduce((a,s)=>a+s,0);return t.map(a=>a/r)}function T1(n){return zn(n).map(r=>Math.log(r))}function W_(n){if(n.length===0)throw Error("Array must not be empty");let e=n[0],t=0;for(let r=1;re&&(e=n[r],t=r);return[Number(e),t]}function V_(n){return n>0&&(n&n-1)===0}class H_{constructor(e){if(this.size=e|0,this.size<=1||!V_(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;rr;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<>>i&3)<>>1);for(let i=0;i>>1]=e[i];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let i=0;i>>1],r[i+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r>=2;s>=2;s>>=2){o=i/s<<1;const p=o>>>2;for(l=0;l>>1,s>>>1)}else for(l=0,u=0;l>>1,s>>>1,r)}const h=this.table;for(s>>=2;s>=2;s>>=2){o=i/s<<1;const d=o>>>1,m=d>>>1,y=m>>>1;for(l=0;l>>1;for(let d=2;d>1;++c){const h=(c+1-e)**2/2,p=Math.sqrt(l**2+u**2)**h,d=h*Math.atan2(u,l),m=2*c;a[m]=p*Math.cos(d),a[m+1]=p*Math.sin(d),s[m]=a[m],s[m+1]=-a[m+1]}this._slicedChirpBuffer=a.subarray(t,r),this._f=new H_(i>>1),this._f.transform(this._chirpBuffer,s)}_transform(e,t,r){const i=this._buffer1,a=this._buffer2,s=this._outBuffer1,o=this._outBuffer2,l=this._chirpBuffer,u=this._slicedChirpBuffer,c=this._a;if(r)for(let h=0;h>1,m=t[d];i[h]=m*u[h],i[p]=m*u[p]}else for(let h=0;h=n.length&&(l=2*(n.length-1)-l),r[s++]=n[l]}r.sort(),t[a]=r[i]}return t}function wl(n,e){const t=Math.pow(10,e);return Math.round(n*t)/t}function R1(n){const e=Math.round(n);return Math.abs(n)%1===.5?e%2===0?e:e-1:e}/*! * ONNX Runtime Web v1.18.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var dd=Object.defineProperty,I1=Object.getOwnPropertyDescriptor,P1=Object.getOwnPropertyNames,k1=Object.prototype.hasOwnProperty,Ce=(n,e)=>()=>(n&&(e=n(n=0)),e),fs=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ms=(n,e)=>{for(var t in e)dd(n,t,{get:e[t],enumerable:!0})},O1=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of P1(e))!k1.call(n,i)&&i!==t&&dd(n,i,{get:()=>e[i],enumerable:!(r=I1(e,i))||r.enumerable});return n},la=n=>O1(dd({},"__esModule",{value:!0}),n),Es,bi,aa,Uh,hd,pd=Ce(()=>{Es=new Map,bi=[],aa=(n,e,t)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let r=Es.get(n);if(r===void 0)Es.set(n,{backend:e,priority:t});else{if(r.priority>t)return;if(r.priority===t&&r.backend!==e)throw new Error(`cannot register backend "${n}" using priority ${t}`)}if(t>=0){let i=bi.indexOf(n);i!==-1&&bi.splice(i,1);for(let a=0;a{let e=Es.get(n);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let t=!!e.initPromise;try{return t||(e.initPromise=e.backend.init(n)),await e.initPromise,e.initialized=!0,e.backend}catch(r){return t||(e.error=`${r}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},hd=async n=>{let e=n.executionProviders||[],t=e.map(l=>typeof l=="string"?l:l.name),r=t.length===0?bi:t,i,a=[],s=new Set;for(let l of r){let u=await Uh(l);typeof u=="string"?a.push({name:l,err:u}):(i||(i=u),i===u&&s.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of a)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let o=e.filter(l=>s.has(typeof l=="string"?l:l.name));return[i,new Proxy(n,{get:(l,u)=>u==="executionProviders"?o:Reflect.get(l,u)})]}}),D1=Ce(()=>{pd()}),q_,L1=Ce(()=>{q_="1.18.0"}),Mu,fr,j_=Ce(()=>{L1(),Mu="warning",fr={wasm:{},webgl:{},webgpu:{},versions:{common:q_},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);Mu=n}},get logLevel(){return Mu}},Object.defineProperty(fr,"logLevel",{enumerable:!0})}),Kt,z1=Ce(()=>{j_(),Kt=fr}),X_,Y_,N1=Ce(()=>{X_=(n,e)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=n.dims[3],t.height=n.dims[2];let r=t.getContext("2d");if(r!=null){let i,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],a=n.dims[3]):(i=n.dims[3],a=n.dims[2]);let s=e?.format!==void 0?e.format:"RGB",o=e?.norm,l,u;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?u=[0,0,0,0]:typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:(u=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(u[3]=o.bias[3]));let c=a*i,h=0,p=c,d=c*2,m=-1;s==="RGBA"?(h=0,p=c,d=c*2,m=c*3):s==="RGB"?(h=0,p=c,d=c*2):s==="RBG"&&(h=0,d=c,p=c*2);for(let y=0;y{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(t!=null){let i,a,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],a=n.dims[1],s=n.dims[3]):(i=n.dims[3],a=n.dims[2],s=n.dims[1]);let o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,u,c;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?c=[0,0,0,0]:typeof l.bias=="number"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[3]=l.bias[3]));let h=a*i;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,d=0,m=1,y=2,g=3,_=0,w=h,b=h*2,E=-1;o==="RGBA"?(_=0,w=h,b=h*2,E=h*3):o==="RGB"?(_=0,w=h,b=h*2):o==="RBG"&&(_=0,b=h,w=h*2),r=t.createImageData(i,a);for(let T=0;T{fd(),Lo=(n,e)=>{if(n===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:r}=e,i=e.norm??{mean:255,bias:0},a,s;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=t*r,c=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),h=4,p=0,d=1,m=2,y=3,g=0,_=u,w=u*2,b=-1;o==="RGB"&&(h=3,p=0,d=1,m=2,y=-1),l==="RGBA"?b=u*3:l==="RBG"?(g=0,w=u,_=u*2):l==="BGR"&&(w=0,_=u,g=u*2);for(let E=0;E{let t=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,r=typeof ImageData<"u"&&n instanceof ImageData,i=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,a=typeof n=="string",s,o=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(t){let c=l();c.width=n.width,c.height=n.height;let h=u(c);if(h!=null){let p=n.height,d=n.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(p=e.resizedHeight,d=e.resizedWidth),e!==void 0){if(o=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=p,o.width=d}else o.tensorFormat="RGBA",o.height=p,o.width=d;h.drawImage(n,0,0),s=h.getImageData(0,0,d,p).data}else throw new Error("Can not access image data")}else if(r){let c,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,h=e.resizedWidth):(c=n.height,h=n.width),e!==void 0&&(o=e),o.format="RGBA",o.height=c,o.width=h,e!==void 0){let p=l();p.width=h,p.height=c;let d=u(p);if(d!=null)d.putImageData(n,0,0),s=d.getImageData(0,0,h,c).data;else throw new Error("Can not access image data")}else s=n.data}else if(i){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let c=l();c.width=n.width,c.height=n.height;let h=u(c);if(h!=null){let p=n.height,d=n.width;return h.drawImage(n,0,0,d,p),s=h.getImageData(0,0,d,p).data,o.height=p,o.width=d,Lo(s,o)}else throw new Error("Can not access image data")}else{if(a)return new Promise((c,h)=>{let p=l(),d=u(p);if(!n||!d)return h();let m=new Image;m.crossOrigin="Anonymous",m.src=n,m.onload=()=>{p.width=m.width,p.height=m.height,d.drawImage(m,0,0,p.width,p.height);let y=d.getImageData(0,0,p.width,p.height);o.height=p.height,o.width=p.width,c(Lo(y.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return Lo(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},Z_=(n,e)=>{let{width:t,height:r,download:i,dispose:a}=e,s=[1,r,t,4];return new Dr({location:"texture",type:"float32",texture:n,dims:s,download:i,dispose:a})},Q_=(n,e)=>{let{dataType:t,dims:r,download:i,dispose:a}=e;return new Dr({location:"gpu-buffer",type:t??"float32",gpuBuffer:n,dims:r,download:i,dispose:a})},J_=(n,e,t)=>new Dr({location:"cpu-pinned",type:n,data:e,dims:t??[e.length]})}),ea,zs,Tu,e0,B1=Ce(()=>{ea=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),zs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Tu=!1,e0=()=>{if(!Tu){Tu=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,t=typeof Float16Array<"u"&&Float16Array.from;n&&(ea.set("int64",BigInt64Array),zs.set(BigInt64Array,"int64")),e&&(ea.set("uint64",BigUint64Array),zs.set(BigUint64Array,"uint64")),t?(ea.set("float16",Float16Array),zs.set(Float16Array,"float16")):ea.set("float16",Uint16Array)}}}),t0,n0,F1=Ce(()=>{fd(),t0=n=>{let e=1;for(let t=0;t{switch(n.location){case"cpu":return new Dr(n.type,n.data,e);case"cpu-pinned":return new Dr({location:"cpu-pinned",data:n.data,type:n.type,dims:e});case"texture":return new Dr({location:"texture",texture:n.texture,type:n.type,dims:e});case"gpu-buffer":return new Dr({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}}}),Dr,fd=Ce(()=>{N1(),U1(),B1(),F1(),Dr=class{constructor(n,e,t){e0();let r,i;if(typeof n=="object"&&"location"in n)switch(this.dataLocation=n.location,r=n.type,i=n.dims,n.location){case"cpu-pinned":{let s=ea.get(r);if(!s)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(n.data instanceof s))throw new TypeError(`buffer should be of type ${s.name}`);this.cpuData=n.data;break}case"texture":{if(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=n.texture,this.downloader=n.download,this.disposer=n.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint8"&&r!=="bool")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=n.gpuBuffer,this.downloader=n.download,this.disposer=n.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,o;if(typeof n=="string")if(r=n,o=t,n==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");s=e}else{let l=ea.get(n);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(e)){if(n==="float16"&&l===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");n==="uint64"||n==="int64"?s=l.from(e,BigInt):s=l.from(e)}else if(e instanceof l)s=e;else throw new TypeError(`A ${r} tensor's data must be type of ${l}`)}else if(o=e,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof n[0];if(l==="string")r="string",s=n;else if(l==="boolean")r="bool",s=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else{let l=zs.get(n.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);r=l,s=n}if(o===void 0)o=[s.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");i=o,this.cpuData=s,this.dataLocation="cpu"}let a=t0(i);if(this.cpuData&&a!==this.cpuData.length)throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(n,e){return K_(n,e)}static fromTexture(n,e){return Z_(n,e)}static fromGpuBuffer(n,e){return Q_(n,e)}static fromPinnedBuffer(n,e,t){return J_(n,e,t)}toDataURL(n){return X_(this,n)}toImageData(n){return Y_(this,n)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(n){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,n&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(n){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return n0(this,n)}}}),jn,md=Ce(()=>{fd(),jn=Dr}),js,Au,Nr,yr,r0=Ce(()=>{j_(),js=(n,e)=>{(typeof fr.trace>"u"?!fr.wasm.trace:!fr.trace)||console.timeStamp(`${n}::ORT::${e}`)},Au=(n,e)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof fr.trace>"u"?!fr.wasm.trace:!fr.trace)||Au("BEGIN",n)},yr=n=>{(typeof fr.trace>"u"?!fr.wasm.trace:!fr.trace)||Au("END",n)}}),i0,G1=Ce(()=>{pd(),md(),r0(),i0=class a0{constructor(e){this.handler=e}async run(e,t,r){Nr();let i={},a={};if(typeof e!="object"||e===null||e instanceof jn||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof jn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);i[u]=null}if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,c=Object.getOwnPropertyNames(t);for(let h of this.outputNames)if(c.indexOf(h)!==-1){let p=t[h];(p===null||p instanceof jn)&&(u=!0,s=!1,i[h]=p)}if(u){if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else a=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof e[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(s)for(let u of this.outputNames)i[u]=null;let o=await this.handler.run(e,i,a),l={};for(let u in o)if(Object.hasOwnProperty.call(o,u)){let c=o[u];c instanceof jn?l[u]=c:l[u]=new jn(c.type,c.data,c.dims)}return yr(),l}async release(){return this.handler.dispose()}static async create(e,t,r,i){Nr();let a,s={};if(typeof e=="string"){if(a=e,typeof t=="object"&&t!==null)s=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(a=e,typeof t=="object"&&t!==null)s=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let c=e,h=0,p=e.byteLength;if(typeof t=="object"&&t!==null)s=t;else if(typeof t=="number"){if(h=t,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.byteLength}).`);if(p=e.byteLength-h,typeof r=="number"){if(p=r,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||h+p>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.byteLength-h}].`);if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(c,h,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await hd(s),u=await o.createInferenceSessionHandler(a,l);return yr(),new a0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),gd,W1=Ce(()=>{G1(),gd=i0}),V1=Ce(()=>{}),H1=Ce(()=>{}),q1=Ce(()=>{}),j1=Ce(()=>{}),Bh,s0,X1=Ce(()=>{pd(),md(),Bh="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",s0=class o0{constructor(e,t,r){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=r}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,t){let r=e.evalModel||"",i=e.optimizerModel||"",a=t||{},[s,o]=await hd(a);if(s.createTrainingSessionHandler){let l=await s.createTrainingSessionHandler(e.checkpointState,e.trainModel,r,i,o);return new o0(l,!!e.optimizerModel,!!e.evalModel)}else throw new Error(Bh)}typeNarrowingForRunStep(e,t,r,i,a){let s={},o={};if(typeof r!="object"||r===null||r instanceof jn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof jn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(let u of i){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(t.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);s[u]=null}if(typeof a=="object"&&a!==null)o=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,c=Object.getOwnPropertyNames(i);for(let h of t)if(c.indexOf(h)!==-1){let p=i[h];(p===null||p instanceof jn)&&(u=!0,l=!1,s[h]=p)}if(u){if(typeof a=="object"&&a!==null)o=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else o=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of e)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(l)for(let u of t)s[u]=null;return[s,o]}convertHandlerReturnTypeToMapOfTensors(e){let t={};for(let r in e)if(Object.hasOwnProperty.call(e,r)){let i=e[r];i instanceof jn?t[r]=i:t[r]=new jn(i.type,i.data,i.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,r){let[i,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,r),s=await this.handler.runTrainStep(e,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}async runOptimizerStep(e){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(e||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(e,t,r){if(this.hasEvalModel){let[i,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,r),s=await this.handler.runEvalStep(e,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,t=!0){let r=await this.getParametersSize(t);if(e.length!==4*r)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,t)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}}),_d,Y1=Ce(()=>{X1(),_d=s0}),l0={};ms(l0,{InferenceSession:()=>gd,TRACE:()=>js,TRACE_FUNC_BEGIN:()=>Nr,TRACE_FUNC_END:()=>yr,Tensor:()=>jn,TrainingSession:()=>_d,env:()=>Kt,registerBackend:()=>aa});var Ur=Ce(()=>{D1(),z1(),W1(),md(),V1(),H1(),r0(),q1(),j1(),Y1()}),yd={};ms(yd,{createReadStream:()=>d0,readFile:()=>u0,readFileSync:()=>c0});var u0,c0,d0,h0=Ce(()=>{u0=void 0,c0=void 0,d0=void 0}),vd={};ms(vd,{join:()=>p0});var p0,f0=Ce(()=>{p0=void 0}),K1=fs((n,e)=>{var t=(()=>{var r=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(r||=__filename),function(i={}){var a=i,s,o,l=new Promise((v,S)=>{s=v,o=S});a.mountExternalData=(v,S)=>{(a.eb||(a.eb=new Map)).set(v,S)},a.unmountExternalData=()=>{delete a.eb};let u=()=>{let v=(A,D,V)=>(...le)=>{let xe=Pn,Ae=D?.();le=A(...le);let Ke=D?.();return Ae!==Ke&&(A=Ke,V(Ae),D=V=null),Pn!=xe?Aa():le},S=A=>async(...D)=>{try{if(a.cb)throw Error("Session already started");let V=a.cb={xb:D[0],errors:[]},le=await A(...D);if(a.cb!==V)throw Error("Session mismatch");a.kb?.flush();let xe=V.errors;if(0Ke),0a._OrtCreateSession,A=>a._OrtCreateSession=A),a._OrtRun=S(v(a._OrtRun,()=>a._OrtRun,A=>a._OrtRun=A)),a._OrtRunWithBinding=S(v(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,A=>a._OrtRunWithBinding=A)),a._OrtBindInput=v(a._OrtBindInput,()=>a._OrtBindInput,A=>a._OrtBindInput=A),u=void 0};a.jsepInit=(v,S)=>{if(u?.(),v==="webgpu"){[a.kb,a.pb,a.tb,a.lb,a.sb,a.Ra,a.ub,a.wb,a.qb,a.rb,a.vb]=S;let A=a.kb;a.jsepRegisterBuffer=(D,V,le,xe)=>A.registerBuffer(D,V,le,xe),a.jsepGetBuffer=D=>A.getBuffer(D),a.jsepCreateDownloader=(D,V,le)=>A.createDownloader(D,V,le),a.jsepOnReleaseSession=D=>{A.onReleaseSession(D)},a.jsepOnRunStart=D=>A.onRunStart(D)}};var c=Object.assign({},a),h="./this.program",p=(v,S)=>{throw S},d=typeof window=="object",m=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="",_,w,b;if(y){var E=(h0(),la(yd)),T=(f0(),la(vd));g=m?T.dirname(g)+"/":__dirname+"/",_=(v,S)=>(v=et(v)?new URL(v):T.normalize(v),E.readFileSync(v,S?void 0:"utf8")),b=v=>(v=_(v,!0),v.buffer||(v=new Uint8Array(v)),v),w=(v,S,A,D=!0)=>{v=et(v)?new URL(v):T.normalize(v),E.readFile(v,D?void 0:"utf8",(V,le)=>{V?A(V):S(D?le.buffer:le)})},!a.thisProgram&&1{throw process.exitCode=v,S}}else(d||m)&&(m?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),r&&(g=r),g.startsWith("blob:")?g="":g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1),_=v=>{var S=new XMLHttpRequest;return S.open("GET",v,!1),S.send(null),S.responseText},m&&(b=v=>{var S=new XMLHttpRequest;return S.open("GET",v,!1),S.responseType="arraybuffer",S.send(null),new Uint8Array(S.response)}),w=(v,S,A)=>{var D=new XMLHttpRequest;D.open("GET",v,!0),D.responseType="arraybuffer",D.onload=()=>{D.status==200||D.status==0&&D.response?S(D.response):A()},D.onerror=A,D.send(null)});var I=console.log.bind(console),C=console.error.bind(console);Object.assign(a,c),c=null;var B,R=!1,k,j,Q,ie,F,$,L,H,K,X,J;function W(){var v=B.buffer;a.HEAP8=j=new Int8Array(v),a.HEAP16=ie=new Int16Array(v),a.HEAPU8=Q=new Uint8Array(v),a.HEAPU16=F=new Uint16Array(v),a.HEAP32=$=new Int32Array(v),a.HEAPU32=L=new Uint32Array(v),a.HEAPF32=H=new Float32Array(v),a.HEAPF64=J=new Float64Array(v),a.HEAP64=K=new BigInt64Array(v),a.HEAPU64=X=new BigUint64Array(v)}var ae=[],Z=[],de=[],ye=0,Pe=null;function ke(v){throw v="Aborted("+v+")",C(v),R=!0,k=1,v=new WebAssembly.RuntimeError(v+". Build with -sASSERTIONS for more info."),o(v),v}var Be=v=>v.startsWith("data:application/octet-stream;base64,"),et=v=>v.startsWith("file://"),De;if(De="ort-wasm-simd.wasm",!Be(De)){var Xe=De;De=a.locateFile?a.locateFile(Xe,g):g+Xe}function te(v){if(b)return b(v);throw"both async and sync fetching of the wasm failed"}function Xt(v){if(d||m){if(typeof fetch=="function"&&!et(v))return fetch(v,{credentials:"same-origin"}).then(S=>{if(!S.ok)throw`failed to load wasm binary file at '${v}'`;return S.arrayBuffer()}).catch(()=>te(v));if(w)return new Promise((S,A)=>{w(v,D=>S(new Uint8Array(D)),A)})}return Promise.resolve().then(()=>te(v))}function Fe(v,S,A){return Xt(v).then(D=>WebAssembly.instantiate(D,S)).then(A,D=>{C(`failed to asynchronously prepare wasm: ${D}`),ke(D)})}function ot(v,S){var A=De;return typeof WebAssembly.instantiateStreaming!="function"||Be(A)||et(A)||y||typeof fetch!="function"?Fe(A,v,S):fetch(A,{credentials:"same-origin"}).then(D=>WebAssembly.instantiateStreaming(D,v).then(S,function(V){return C(`wasm streaming compile failed: ${V}`),C("falling back to ArrayBuffer instantiation"),Fe(A,v,S)}))}var Ve={824920:(v,S,A,D)=>{if(typeof a>"u"||!a.eb)return 1;if(v=ge(v>>>0),v.startsWith("./")&&(v=v.substring(2)),v=a.eb.get(v),!v)return 2;if(S>>>=0,A>>>=0,S+A>v.byteLength)return 3;try{return Q.set(v.subarray(S,S+A),D>>>0>>>0),0}catch{return 4}},825421:()=>{a.qb()},825452:()=>{a.rb()},825481:()=>{a.vb()},825506:v=>a.pb(v),825539:v=>a.tb(v),825571:(v,S,A)=>{a.lb(v,S,A,!0)},825610:(v,S,A)=>{a.lb(v,S,A)},825643:v=>{a.Ra("Abs",v,void 0)},825694:v=>{a.Ra("Neg",v,void 0)},825745:v=>{a.Ra("Floor",v,void 0)},825798:v=>{a.Ra("Ceil",v,void 0)},825850:v=>{a.Ra("Reciprocal",v,void 0)},825908:v=>{a.Ra("Sqrt",v,void 0)},825960:v=>{a.Ra("Exp",v,void 0)},826011:v=>{a.Ra("Erf",v,void 0)},826062:v=>{a.Ra("Sigmoid",v,void 0)},826117:(v,S,A)=>{a.Ra("HardSigmoid",v,{alpha:S,beta:A})},826196:v=>{a.Ra("Log",v,void 0)},826247:v=>{a.Ra("Sin",v,void 0)},826298:v=>{a.Ra("Cos",v,void 0)},826349:v=>{a.Ra("Tan",v,void 0)},826400:v=>{a.Ra("Asin",v,void 0)},826452:v=>{a.Ra("Acos",v,void 0)},826504:v=>{a.Ra("Atan",v,void 0)},826556:v=>{a.Ra("Sinh",v,void 0)},826608:v=>{a.Ra("Cosh",v,void 0)},826660:v=>{a.Ra("Asinh",v,void 0)},826713:v=>{a.Ra("Acosh",v,void 0)},826766:v=>{a.Ra("Atanh",v,void 0)},826819:v=>{a.Ra("Tanh",v,void 0)},826871:v=>{a.Ra("Not",v,void 0)},826922:(v,S,A)=>{a.Ra("Clip",v,{min:S,max:A})},826991:v=>{a.Ra("Clip",v,void 0)},827043:(v,S)=>{a.Ra("Elu",v,{alpha:S})},827101:v=>{a.Ra("Relu",v,void 0)},827153:(v,S)=>{a.Ra("LeakyRelu",v,{alpha:S})},827217:(v,S)=>{a.Ra("ThresholdedRelu",v,{alpha:S})},827287:(v,S)=>{a.Ra("Cast",v,{to:S})},827345:v=>{a.Ra("Add",v,void 0)},827396:v=>{a.Ra("Sub",v,void 0)},827447:v=>{a.Ra("Mul",v,void 0)},827498:v=>{a.Ra("Div",v,void 0)},827549:v=>{a.Ra("Pow",v,void 0)},827600:v=>{a.Ra("Equal",v,void 0)},827653:v=>{a.Ra("Greater",v,void 0)},827708:v=>{a.Ra("GreaterOrEqual",v,void 0)},827770:v=>{a.Ra("Less",v,void 0)},827822:v=>{a.Ra("LessOrEqual",v,void 0)},827881:(v,S,A,D,V)=>{a.Ra("ReduceMean",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},828040:(v,S,A,D,V)=>{a.Ra("ReduceMax",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},828198:(v,S,A,D,V)=>{a.Ra("ReduceMin",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},828356:(v,S,A,D,V)=>{a.Ra("ReduceProd",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},828515:(v,S,A,D,V)=>{a.Ra("ReduceSum",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},828673:(v,S,A,D,V)=>{a.Ra("ReduceL1",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},828830:(v,S,A,D,V)=>{a.Ra("ReduceL2",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},828987:(v,S,A,D,V)=>{a.Ra("ReduceLogSum",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},829148:(v,S,A,D,V)=>{a.Ra("ReduceSumSquare",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},829312:(v,S,A,D,V)=>{a.Ra("ReduceLogSumExp",v,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},829476:v=>{a.Ra("Where",v,void 0)},829529:(v,S,A)=>{a.Ra("Transpose",v,{perm:S?Array.from($.subarray(S>>>0,A>>>0)):[]})},829637:(v,S,A,D)=>{a.Ra("DepthToSpace",v,{blocksize:S,mode:ge(A),format:D?"NHWC":"NCHW"})},829770:(v,S,A,D)=>{a.Ra("DepthToSpace",v,{blocksize:S,mode:ge(A),format:D?"NHWC":"NCHW"})},829903:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce,St)=>{a.Ra("ConvTranspose",v,{format:Ke?"NHWC":"NCHW",autoPad:S,dilations:[A],group:D,kernelShape:[V],pads:[le,xe],strides:[Ae],wIsConst:()=>!!j[Ne>>>0],outputPadding:st?Array.from($.subarray(st>>>0,Bt>>>0)):[],outputShape:Ht?Array.from($.subarray(Ht>>>0,ce>>>0)):[],activation:ge(St)})},830304:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce)=>{a.Ra("ConvTranspose",v,{format:Ae?"NHWC":"NCHW",autoPad:S,dilations:Array.from($.subarray(A>>>0,(A>>>0)+2>>>0)),group:D,kernelShape:Array.from($.subarray(V>>>0,(V>>>0)+2>>>0)),pads:Array.from($.subarray(le>>>0,(le>>>0)+4>>>0)),strides:Array.from($.subarray(xe>>>0,(xe>>>0)+2>>>0)),wIsConst:()=>!!j[Ke>>>0],outputPadding:Ne?Array.from($.subarray(Ne>>>0,st>>>0)):[],outputShape:Bt?Array.from($.subarray(Bt>>>0,Ht>>>0)):[],activation:ge(ce)})},830869:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce,St)=>{a.Ra("ConvTranspose",v,{format:Ke?"NHWC":"NCHW",autoPad:S,dilations:[A],group:D,kernelShape:[V],pads:[le,xe],strides:[Ae],wIsConst:()=>!!j[Ne>>>0],outputPadding:st?Array.from($.subarray(st>>>0,Bt>>>0)):[],outputShape:Ht?Array.from($.subarray(Ht>>>0,ce>>>0)):[],activation:ge(St)})},831270:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce)=>{a.Ra("ConvTranspose",v,{format:Ae?"NHWC":"NCHW",autoPad:S,dilations:Array.from($.subarray(A>>>0,(A>>>0)+2>>>0)),group:D,kernelShape:Array.from($.subarray(V>>>0,(V>>>0)+2>>>0)),pads:Array.from($.subarray(le>>>0,(le>>>0)+4>>>0)),strides:Array.from($.subarray(xe>>>0,(xe>>>0)+2>>>0)),wIsConst:()=>!!j[Ke>>>0],outputPadding:Ne?Array.from($.subarray(Ne>>>0,st>>>0)):[],outputShape:Bt?Array.from($.subarray(Bt>>>0,Ht>>>0)):[],activation:ge(ce)})},831835:(v,S)=>{a.Ra("GlobalAveragePool",v,{format:S?"NHWC":"NCHW"})},831926:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce,St,Ut)=>{a.Ra("AveragePool",v,{format:Ut?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:D,storage_order:V,dilations:[le,xe],kernel_shape:[Ae,Ke],pads:[Ne,st,Bt,Ht],strides:[ce,St]})},832210:(v,S)=>{a.Ra("GlobalAveragePool",v,{format:S?"NHWC":"NCHW"})},832301:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce,St,Ut)=>{a.Ra("AveragePool",v,{format:Ut?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:D,storage_order:V,dilations:[le,xe],kernel_shape:[Ae,Ke],pads:[Ne,st,Bt,Ht],strides:[ce,St]})},832585:(v,S)=>{a.Ra("GlobalMaxPool",v,{format:S?"NHWC":"NCHW"})},832672:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce,St,Ut)=>{a.Ra("MaxPool",v,{format:Ut?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:D,storage_order:V,dilations:[le,xe],kernel_shape:[Ae,Ke],pads:[Ne,st,Bt,Ht],strides:[ce,St]})},832952:(v,S)=>{a.Ra("GlobalMaxPool",v,{format:S?"NHWC":"NCHW"})},833039:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce,St,Ut)=>{a.Ra("MaxPool",v,{format:Ut?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:D,storage_order:V,dilations:[le,xe],kernel_shape:[Ae,Ke],pads:[Ne,st,Bt,Ht],strides:[ce,St]})},833319:(v,S,A,D,V)=>{a.Ra("Gemm",v,{alpha:S,beta:A,transA:D,transB:V})},833423:v=>{a.Ra("MatMul",v,void 0)},833477:(v,S,A,D)=>{a.Ra("ArgMax",v,{keepDims:!!S,selectLastIndex:!!A,axis:D})},833585:(v,S,A,D)=>{a.Ra("ArgMin",v,{keepDims:!!S,selectLastIndex:!!A,axis:D})},833693:(v,S)=>{a.Ra("Softmax",v,{axis:S})},833756:(v,S)=>{a.Ra("Concat",v,{axis:S})},833816:(v,S,A,D,V)=>{a.Ra("Split",v,{axis:S,numOutputs:A,splitSizes:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},833956:v=>{a.Ra("Expand",v,void 0)},834010:(v,S)=>{a.Ra("Gather",v,{axis:Number(S)})},834081:(v,S)=>{a.Ra("GatherElements",v,{axis:Number(S)})},834160:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st)=>{a.Ra("Resize",v,{antialias:S,axes:A?Array.from($.subarray(A>>>0,D>>>0)):[],coordinateTransformMode:ge(V),cubicCoeffA:le,excludeOutside:xe,extrapolationValue:Ae,keepAspectRatioPolicy:ge(Ke),mode:ge(Ne),nearestMode:ge(st)})},834506:(v,S,A,D,V,le,xe)=>{a.Ra("Slice",v,{starts:S?Array.from($.subarray(S>>>0,A>>>0)):[],ends:D?Array.from($.subarray(D>>>0,V>>>0)):[],axes:le?Array.from($.subarray(le>>>0,xe>>>0)):[]})},834722:v=>{a.Ra("Tile",v,void 0)},834774:(v,S,A,D)=>{a.Ra("LayerNormalization",v,{axis:S,epsilon:A,simplified:!!D})},834885:(v,S,A)=>{a.Ra("InstanceNormalization",v,{epsilon:S,format:A?"NHWC":"NCHW"})},834999:(v,S,A)=>{a.Ra("InstanceNormalization",v,{epsilon:S,format:A?"NHWC":"NCHW"})},835113:v=>{a.Ra("Range",v,void 0)},835166:(v,S)=>{a.Ra("Einsum",v,{equation:ge(S)})},835247:(v,S,A,D,V)=>{a.Ra("Pad",v,{mode:S,value:A,pads:D?Array.from($.subarray(D>>>0,V>>>0)):[]})},835374:(v,S,A,D,V,le)=>{a.Ra("BatchNormalization",v,{epsilon:S,momentum:A,spatial:!!V,trainingMode:!!D,format:le?"NHWC":"NCHW"})},835543:(v,S,A,D,V,le)=>{a.Ra("BatchNormalization",v,{epsilon:S,momentum:A,spatial:!!V,trainingMode:!!D,format:le?"NHWC":"NCHW"})},835712:(v,S,A)=>{a.Ra("CumSum",v,{exclusive:Number(S),reverse:Number(A)})},835809:(v,S,A,D,V,le,xe,Ae,Ke)=>{a.Ra("Attention",v,{numHeads:S,isUnidirectional:A,maskFilterValue:D,scale:V,doRotary:le,qkvHiddenSizes:xe?Array.from($.subarray(Number(Ae)>>>0,Number(Ae)+xe>>>0)):[],pastPresentShareBuffer:!!Ke})},836081:v=>{a.Ra("BiasAdd",v,void 0)},836136:v=>{a.Ra("BiasSplitGelu",v,void 0)},836197:v=>{a.Ra("FastGelu",v,void 0)},836253:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht)=>{a.Ra("Conv",v,{format:Ke?"NHWC":"NCHW",auto_pad:S,dilations:[A],group:D,kernel_shape:[V],pads:le?Array.from($.subarray(le>>>0,xe>>>0)):[],strides:[Ae],w_is_const:()=>!!j[Ne>>>0],activation:ge(st),activation_params:Bt?Array.from(H.subarray(Bt>>>0,Ht>>>0)):[]})},836623:(v,S,A,D,V,le,xe,Ae,Ke,Ne,st,Bt,Ht,ce,St,Ut)=>{a.Ra("Conv",v,{format:Bt?"NHWC":"NCHW",auto_pad:S,dilations:[A,D],group:V,kernel_shape:[le,xe],pads:Ae?Array.from($.subarray(Ae>>>0,Ke>>>0)):[],strides:[Ne,st],w_is_const:()=>!!j[Ht>>>0],activation:ge(ce),activation_params:St?Array.from(H.subarray(St>>>0,Ut>>>0)):[]})},837014:v=>{a.Ra("Gelu",v,void 0)},837066:(v,S,A,D,V,le)=>{a.Ra("MatMulNBits",v,{k:S,n:A,accuracyLevel:D,bits:V,blockSize:le})},837193:(v,S,A,D,V,le)=>{a.Ra("MultiHeadAttention",v,{numHeads:S,isUnidirectional:A,maskFilterValue:D,scale:V,doRotary:le})},837352:(v,S,A,D,V)=>{a.Ra("RotaryEmbedding",v,{interleaved:!!S,numHeads:A,rotaryEmbeddingDim:D,scale:V})},837491:(v,S,A)=>{a.Ra("SkipLayerNormalization",v,{epsilon:S,simplified:!!A})},837593:(v,S,A)=>{a.Ra("SkipLayerNormalization",v,{epsilon:S,simplified:!!A})},837695:(v,S,A,D)=>{a.Ra("LayerNormalization",v,{axis:S,epsilon:A,simplified:!!D})},837806:v=>{a.ub(v)},837840:(v,S)=>a.wb(v,S,a.cb.xb,a.cb.errors)};function zt(v){this.name="ExitStatus",this.message=`Program terminated with exit(${v})`,this.status=v}class xt{constructor(S){this.hb=S-24}}var N=0,O=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ne=(v,S,A)=>{S>>>=0;var D=S+A;for(A=S;v[A]&&!(A>=D);)++A;if(16V?D+=String.fromCharCode(V):(V-=65536,D+=String.fromCharCode(55296|V>>10,56320|V&1023))}}else D+=String.fromCharCode(V)}return D},ge=(v,S)=>(v>>>=0)?ne(Q,v,S):"",we=v=>{for(var S=0,A=0;A=D?S++:2047>=D?S+=2:55296<=D&&57343>=D?(S+=4,++A):S+=3}return S},_e=(v,S,A,D)=>{if(A>>>=0,!(0=xe){var Ae=v.charCodeAt(++le);xe=65536+((xe&1023)<<10)|Ae&1023}if(127>=xe){if(A>=D)break;S[A++>>>0]=xe}else{if(2047>=xe){if(A+1>=D)break;S[A++>>>0]=192|xe>>6}else{if(65535>=xe){if(A+2>=D)break;S[A++>>>0]=224|xe>>12}else{if(A+3>=D)break;S[A++>>>0]=240|xe>>18,S[A++>>>0]=128|xe>>12&63}S[A++>>>0]=128|xe>>6&63}S[A++>>>0]=128|xe&63}}return S[A>>>0]=0,A-V},Ye,Re=v=>{for(var S="";Q[v>>>0];)S+=Ye[Q[v++>>>0]];return S},We={},nt={},dt;function be(v,S,A={}){var D=S.name;if(!v)throw new dt(`type "${D}" must have a positive integer typeid pointer`);if(nt.hasOwnProperty(v)){if(A.nb)return;throw new dt(`Cannot register type '${D}' twice`)}nt[v]=S,We.hasOwnProperty(v)&&(S=We[v],delete We[v],S.forEach(V=>V()))}function yt(v,S,A={}){if(!("argPackAdvance"in S))throw new TypeError("registerType registeredInstance requires argPackAdvance");return be(v,S,A)}var vt=(v,S,A)=>{switch(S){case 1:return A?D=>j[D>>>0]:D=>Q[D>>>0];case 2:return A?D=>ie[D>>>1>>>0]:D=>F[D>>>1>>>0];case 4:return A?D=>$[D>>>2>>>0]:D=>L[D>>>2>>>0];case 8:return A?D=>K[D>>>3]:D=>X[D>>>3];default:throw new TypeError(`invalid integer width (${S}): ${v}`)}},ht=[],Ue=[];function Le(v){v>>>=0,9{if(!v)throw new dt("Cannot use deleted val. handle = "+v);return Ue[v]},ve=v=>{switch(v){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let S=ht.pop()||Ue.length;return Ue[S]=v,Ue[S+1]=1,S}};function Ze(v){return this.fromWireType(L[v>>>2>>>0])}var He={name:"emscripten::val",fromWireType:v=>{var S=U(v);return Le(v),S},toWireType:(v,S)=>ve(S),argPackAdvance:8,readValueFromPointer:Ze,bb:null},Se=(v,S)=>{switch(S){case 4:return function(A){return this.fromWireType(H[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(J[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${S}): ${v}`)}},q=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,fe=(v,S)=>{for(var A=v>>1,D=A+S/2;!(A>=D)&&F[A>>>0];)++A;if(A<<=1,32>>0,A>>>0));for(A="",D=0;!(D>=S/2);++D){var V=ie[v+2*D>>>1>>>0];if(V==0)break;A+=String.fromCharCode(V)}return A},Ie=(v,S,A)=>{if(A??=2147483647,2>A)return 0;A-=2;var D=S;A=A<2*v.length?A/2:v.length;for(var V=0;V>>1>>>0]=v.charCodeAt(V),S+=2;return ie[S>>>1>>>0]=0,S-D},lt=v=>2*v.length,it=(v,S)=>{for(var A=0,D="";!(A>=S/4);){var V=$[v+4*A>>>2>>>0];if(V==0)break;++A,65536<=V?(V-=65536,D+=String.fromCharCode(55296|V>>10,56320|V&1023)):D+=String.fromCharCode(V)}return D},Ct=(v,S,A)=>{if(S>>>=0,A??=2147483647,4>A)return 0;var D=S;A=D+A-4;for(var V=0;V=le){var xe=v.charCodeAt(++V);le=65536+((le&1023)<<10)|xe&1023}if($[S>>>2>>>0]=le,S+=4,S+4>A)break}return $[S>>>2>>>0]=0,S-D},$t=v=>{for(var S=0,A=0;A=D&&++A,S+=4}return S},Yt=(v,S)=>{var A=nt[v];if(A===void 0)throw v=Jr(v),A=Re(v),xn(v),new dt(`${S} has unknown type ${A}`);return A},Jt=(v,S,A)=>{var D=[];return v=v.toWireType(D,A),D.length&&(L[S>>>2>>>0]=ve(D)),v},It=v=>{try{v()}catch(S){ke(S)}},Rt=v=>{if(!R)try{v();try{k=k=v=k,a.onExit?.(v),R=!0,p(v,new zt(v))}catch(S){S instanceof zt||S=="unwind"||p(1,S)}}catch(S){S instanceof zt||S=="unwind"||p(1,S)}};function Fn(){var v=Qe,S={};for(let[A,D]of Object.entries(v))S[A]=typeof D=="function"?(...V)=>{Zn.push(A);try{return D(...V)}finally{R||(Zn.pop(),Pn&&Kn===1&&Zn.length===0&&(Kn=0,It(Co),typeof Fibers<"u"&&Fibers.Db()))}}:D;return S}var Kn=0,Pn=null,Br=0,Zn=[],Fr={},_i={},Bi=0,yi=null,Ta=[];function Aa(){return new Promise((v,S)=>{yi={resolve:v,reject:S}})}function z(){var v=Gr(65548),S=v+12;L[v>>>2>>>0]=S,L[v+4>>>2>>>0]=S+65536,S=Zn[0];var A=Fr[S];return A===void 0&&(A=Bi++,Fr[S]=A,_i[A]=S),$[v+8>>>2>>>0]=A,v}function ee(v){if(!R){if(Kn===0){var S=!1,A=!1;v((D=0)=>{if(!R&&(Br=D,S=!0,A)){Kn=2,It(()=>Sr(Pn)),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.resume(),D=!1;try{var V=(0,Qe[_i[$[Pn+8>>>2>>>0]]])()}catch(Ae){V=Ae,D=!0}var le=!1;if(!Pn){var xe=yi;xe&&(yi=null,(D?xe.reject:xe.resolve)(V),le=!0)}if(D&&!le)throw V}}),A=!0,S||(Kn=1,Pn=z(),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.pause(),It(()=>Gi(Pn)))}else Kn===2?(Kn=0,It(ar),xn(Pn),Pn=null,Ta.forEach(Rt)):ke(`invalid state: ${Kn}`);return Br}}function oe(v){return ee(S=>{v().then(S)})}var ue=[],se={},ze=v=>{var S=se[v];return S===void 0?Re(v):S},qe=()=>typeof globalThis=="object"?globalThis:Function("return this")(),at=v=>{var S=ue.length;return ue.push(v),S},ft=(v,S)=>{for(var A=Array(v),D=0;D>>2>>>0],"parameter "+D);return A},mt=(v,S)=>Object.defineProperty(S,"name",{value:v});function wt(v){var S=Function;if(!(S instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof S} which is not a function`);var A=mt(S.name||"unknownFunctionName",function(){});return A.prototype=S.prototype,A=new A,v=S.apply(A,v),v instanceof Object?v:A}var rt=v=>v%4===0&&(v%100!==0||v%400===0),en=[0,31,60,91,121,152,182,213,244,274,305,335],gn=[0,31,59,90,120,151,181,212,243,273,304,334],Wt=[],kn=(v,S)=>{Wt.length=0;for(var A;A=Q[v++>>>0];){var D=A!=105;D&=A!=112,S+=D&&S%8?4:0,Wt.push(A==112?L[S>>>2>>>0]:A==106?K[S>>>3]:A==105?$[S>>>2>>>0]:J[S>>>3>>>0]),S+=D?8:4}return Wt},Mt={},ut=()=>{if(!xr){var v={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:h||"./this.program"},S;for(S in Mt)Mt[S]===void 0?delete v[S]:v[S]=Mt[S];var A=[];for(S in v)A.push(`${S}=${v[S]}`);xr=A}return xr},xr,tn=[null,[],[]],cr=[31,29,31,30,31,30,31,31,30,31,30,31],vi=[31,28,31,30,31,30,31,31,30,31,30,31];function Qr(v){var S=Array(we(v)+1);return _e(v,S,0,S.length),S}function wi(v,S,A,D){function V(ce,St,Ut){for(ce=typeof ce=="number"?ce.toString():ce||"";ce.lengthni?-1:0ti-ce.getDate())St-=ti-ce.getDate()+1,ce.setDate(1),11>Ut?ce.setMonth(Ut+1):(ce.setMonth(0),ce.setFullYear(ce.getFullYear()+1));else{ce.setDate(ce.getDate()+St);break}}return Ut=new Date(ce.getFullYear()+1,0,4),St=Ae(new Date(ce.getFullYear(),0,4)),Ut=Ae(Ut),0>=xe(St,ce)?0>=xe(Ut,ce)?ce.getFullYear()+1:ce.getFullYear():ce.getFullYear()-1}v>>>=0,S>>>=0,A>>>=0,D>>>=0;var Ne=L[D+40>>>2>>>0];D={Ab:$[D>>>2>>>0],zb:$[D+4>>>2>>>0],fb:$[D+8>>>2>>>0],jb:$[D+12>>>2>>>0],gb:$[D+16>>>2>>>0],ab:$[D+20>>>2>>>0],Va:$[D+24>>>2>>>0],$a:$[D+28>>>2>>>0],Cb:$[D+32>>>2>>>0],yb:$[D+36>>>2>>>0],Bb:Ne?ge(Ne):""},A=ge(A),Ne={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var st in Ne)A=A.replace(new RegExp(st,"g"),Ne[st]);var Bt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ht="January February March April May June July August September October November December".split(" ");Ne={"%a":ce=>Bt[ce.Va].substring(0,3),"%A":ce=>Bt[ce.Va],"%b":ce=>Ht[ce.gb].substring(0,3),"%B":ce=>Ht[ce.gb],"%C":ce=>le((ce.ab+1900)/100|0,2),"%d":ce=>le(ce.jb,2),"%e":ce=>V(ce.jb,2," "),"%g":ce=>Ke(ce).toString().substring(2),"%G":Ke,"%H":ce=>le(ce.fb,2),"%I":ce=>(ce=ce.fb,ce==0?ce=12:12{for(var St=0,Ut=0;Ut<=ce.gb-1;St+=(rt(ce.ab+1900)?cr:vi)[Ut++]);return le(ce.jb+St,3)},"%m":ce=>le(ce.gb+1,2),"%M":ce=>le(ce.zb,2),"%n":()=>` `,"%p":ce=>0<=ce.fb&&12>ce.fb?"AM":"PM","%S":ce=>le(ce.Ab,2),"%t":()=>" ","%u":ce=>ce.Va||7,"%U":ce=>le(Math.floor((ce.$a+7-ce.Va)/7),2),"%V":ce=>{var St=Math.floor((ce.$a+7-(ce.Va+6)%7)/7);if(2>=(ce.Va+371-ce.$a-2)%7&&St++,St)St==53&&(Ut=(ce.Va+371-ce.$a)%7,Ut==4||Ut==3&&rt(ce.ab)||(St=1));else{St=52;var Ut=(ce.Va+7-ce.$a-1)%7;(Ut==4||Ut==5&&rt(ce.ab%400-1))&&St++}return le(St,2)},"%w":ce=>ce.Va,"%W":ce=>le(Math.floor((ce.$a+7-(ce.Va+6)%7)/7),2),"%y":ce=>(ce.ab+1900).toString().substring(2),"%Y":ce=>ce.ab+1900,"%z":ce=>{ce=ce.yb;var St=0<=ce;return ce=Math.abs(ce)/60,(St?"+":"-")+("0000"+(ce/60*100+ce%60)).slice(-4)},"%Z":ce=>ce.Bb,"%%":()=>"%"},A=A.replace(/%%/g,"\0\0");for(st in Ne)A.includes(st)&&(A=A.replace(new RegExp(st,"g"),Ne[st](D)));return A=A.replace(/\0\0/g,"%"),st=Qr(A),st.length>S?0:(j.set(st,v>>>0),st.length-1)}for(var hn=Array(256),Qn=0;256>Qn;++Qn)hn[Qn]=String.fromCharCode(Qn);Ye=hn,dt=a.BindingError=class extends Error{constructor(v){super(v),this.name="BindingError"}},a.InternalError=class extends Error{constructor(v){super(v),this.name="InternalError"}},Ue.push(0,1,void 0,1,null,1,!0,1,!1,1),a.count_emval_handles=()=>Ue.length/2-5-ht.length;var Fi={ia:function(v,S,A){return oe(async()=>{await a.sb(v,S,A)})},a:function(v,S,A){v>>>=0;var D=new xt(v);throw L[D.hb+16>>>2>>>0]=0,L[D.hb+4>>>2>>>0]=S>>>0,L[D.hb+8>>>2>>>0]=A>>>0,N=v,N},y:function(){return 0},ea:function(){},R:function(){},T:function(){},ga:function(){return 0},ca:function(){},Z:function(){},ba:function(){},G:function(){},S:function(){},P:function(){},da:function(){},Q:function(){},C:function(v,S,A){S=Re(S>>>0),yt(v>>>0,{name:S,fromWireType:D=>D,toWireType:function(D,V){if(typeof V!="bigint"&&typeof V!="number")throw V===null?V="null":(D=typeof V,V=D==="object"||D==="array"||D==="function"?V.toString():""+V),new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},argPackAdvance:8,readValueFromPointer:vt(S,A>>>0,S.indexOf("u")==-1),bb:null})},K:function(v,S,A,D){S=Re(S>>>0),yt(v>>>0,{name:S,fromWireType:function(V){return!!V},toWireType:function(V,le){return le?A:D},argPackAdvance:8,readValueFromPointer:function(V){return this.fromWireType(Q[V>>>0])},bb:null})},J:function(v){return yt(v>>>0,He)},B:function(v,S,A){S=Re(S>>>0),yt(v>>>0,{name:S,fromWireType:D=>D,toWireType:(D,V)=>V,argPackAdvance:8,readValueFromPointer:Se(S,A>>>0),bb:null})},s:function(v,S,A,D,V){if(v>>>=0,A>>>=0,S=Re(S>>>0),V===-1&&(V=4294967295),V=Ae=>Ae,D===0){var le=32-8*A;V=Ae=>Ae<>>le}var xe=S.includes("unsigned")?function(Ae,Ke){return Ke>>>0}:function(Ae,Ke){return Ke};yt(v,{name:S,fromWireType:V,toWireType:xe,argPackAdvance:8,readValueFromPointer:vt(S,A,D!==0),bb:null})},o:function(v,S,A){function D(le){return new V(j.buffer,L[le+4>>>2>>>0],L[le>>>2>>>0])}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][S];A=Re(A>>>0),yt(v>>>0,{name:A,fromWireType:D,argPackAdvance:8,readValueFromPointer:D},{nb:!0})},D:function(v,S){S=Re(S>>>0);var A=S==="std::string";yt(v>>>0,{name:S,fromWireType:function(D){var V=L[D>>>2>>>0],le=D+4;if(A)for(var xe=le,Ae=0;Ae<=V;++Ae){var Ke=le+Ae;if(Ae==V||Q[Ke>>>0]==0){if(xe=ge(xe,Ke-xe),Ne===void 0)var Ne=xe;else Ne+="\0",Ne+=xe;xe=Ke+1}}else{for(Ne=Array(V),Ae=0;Ae>>0]);Ne=Ne.join("")}return xn(D),Ne},toWireType:function(D,V){V instanceof ArrayBuffer&&(V=new Uint8Array(V));var le=typeof V=="string";if(!(le||V instanceof Uint8Array||V instanceof Uint8ClampedArray||V instanceof Int8Array))throw new dt("Cannot pass non-string to std::string");var xe=A&&le?we(V):V.length,Ae=Gr(4+xe+1),Ke=Ae+4;if(L[Ae>>>2>>>0]=xe,A&&le)_e(V,Q,Ke,xe+1);else if(le)for(le=0;le>>0]=Ne}else for(le=0;le>>0]=V[le];return D!==null&&D.push(xn,Ae),Ae},argPackAdvance:8,readValueFromPointer:Ze,bb(D){xn(D)}})},x:function(v,S,A){if(S>>>=0,A>>>=0,A=Re(A),S===2)var D=fe,V=Ie,le=lt,xe=Ae=>F[Ae>>>1>>>0];else S===4&&(D=it,V=Ct,le=$t,xe=Ae=>L[Ae>>>2>>>0]);yt(v>>>0,{name:A,fromWireType:Ae=>{for(var Ke=L[Ae>>>2>>>0],Ne,st=Ae+4,Bt=0;Bt<=Ke;++Bt){var Ht=Ae+4+Bt*S;(Bt==Ke||xe(Ht)==0)&&(st=D(st,Ht-st),Ne===void 0?Ne=st:(Ne+="\0",Ne+=st),st=Ht+S)}return xn(Ae),Ne},toWireType:(Ae,Ke)=>{if(typeof Ke!="string")throw new dt(`Cannot pass non-string to C++ string type ${A}`);var Ne=le(Ke),st=Gr(4+Ne+S);return L[st>>>2>>>0]=Ne/S,V(Ke,st+4,Ne+S),Ae!==null&&Ae.push(xn,st),st},argPackAdvance:8,readValueFromPointer:Ze,bb(Ae){xn(Ae)}})},L:function(v,S){S=Re(S>>>0),yt(v>>>0,{ob:!0,name:S,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ha:()=>1,u:function(v,S,A){return S>>>=0,A>>>=0,v=U(v>>>0),S=Yt(S,"emval::as"),Jt(S,A,v)},w:function(v){return v>>>=0,oe(()=>(v=U(v),v.then(ve)))},n:function(v,S,A,D){return A>>>=0,D>>>=0,v=ue[v>>>0],S=U(S>>>0),v(null,S,A,D)},j:function(v,S,A,D,V){return A>>>=0,D>>>=0,V>>>=0,v=ue[v>>>0],S=U(S>>>0),A=ze(A),v(S,S[A],D,V)},b:Le,A:function(v,S){return S>>>=0,v=U(v>>>0),S=U(S),v==S},m:function(v){return v>>>=0,v===0?ve(qe()):(v=ze(v),ve(qe()[v]))},i:function(v,S,A){S=ft(v,S>>>0);var D=S.shift();v--;var V=`return function (obj, func, destructorsRef, args) { `,le=0,xe=[];A===0&&xe.push("obj");for(var Ae=["retType"],Ke=[D],Ne=0;Nest.name).join(", ")}) => ${D.name}>`,at(mt(A,v))},r:function(v,S){return S>>>=0,v=U(v>>>0),S=U(S),ve(v[S])},e:function(v){v>>>=0,9>>0);for(var S=Array(v.length),A=0;A>>0))},k:function(){return ve({})},h:function(v){v>>>=0;for(var S=U(v);S.length;){var A=S.pop();S.pop()(A)}Le(v)},g:function(v,S,A){S>>>=0,A>>>=0,v=U(v>>>0),S=U(S),A=U(A),v[S]=A},c:function(v,S){return S>>>=0,v=Yt(v>>>0,"_emval_take_value"),v=v.readValueFromPointer(S),ve(v)},W:function(v,S){v=-9007199254740992>v||9007199254740992>>=0,v=new Date(1e3*v),$[S>>>2>>>0]=v.getUTCSeconds(),$[S+4>>>2>>>0]=v.getUTCMinutes(),$[S+8>>>2>>>0]=v.getUTCHours(),$[S+12>>>2>>>0]=v.getUTCDate(),$[S+16>>>2>>>0]=v.getUTCMonth(),$[S+20>>>2>>>0]=v.getUTCFullYear()-1900,$[S+24>>>2>>>0]=v.getUTCDay(),$[S+28>>>2>>>0]=(v.getTime()-Date.UTC(v.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},X:function(v,S){v=-9007199254740992>v||9007199254740992>>=0,v=new Date(1e3*v),$[S>>>2>>>0]=v.getSeconds(),$[S+4>>>2>>>0]=v.getMinutes(),$[S+8>>>2>>>0]=v.getHours(),$[S+12>>>2>>>0]=v.getDate(),$[S+16>>>2>>>0]=v.getMonth(),$[S+20>>>2>>>0]=v.getFullYear()-1900,$[S+24>>>2>>>0]=v.getDay(),$[S+28>>>2>>>0]=(rt(v.getFullYear())?en:gn)[v.getMonth()]+v.getDate()-1|0,$[S+36>>>2>>>0]=-(60*v.getTimezoneOffset());var A=new Date(v.getFullYear(),6,1).getTimezoneOffset(),D=new Date(v.getFullYear(),0,1).getTimezoneOffset();$[S+32>>>2>>>0]=(A!=D&&v.getTimezoneOffset()==Math.min(D,A))|0},Y:function(v){v>>>=0;var S=new Date($[v+20>>>2>>>0]+1900,$[v+16>>>2>>>0],$[v+12>>>2>>>0],$[v+8>>>2>>>0],$[v+4>>>2>>>0],$[v>>>2>>>0],0),A=$[v+32>>>2>>>0],D=S.getTimezoneOffset(),V=new Date(S.getFullYear(),6,1).getTimezoneOffset(),le=new Date(S.getFullYear(),0,1).getTimezoneOffset(),xe=Math.min(le,V);return 0>A?$[v+32>>>2>>>0]=+(V!=le&&xe==D):0>>2>>>0]=S.getDay(),$[v+28>>>2>>>0]=(rt(S.getFullYear())?en:gn)[S.getMonth()]+S.getDate()-1|0,$[v>>>2>>>0]=S.getSeconds(),$[v+4>>>2>>>0]=S.getMinutes(),$[v+8>>>2>>>0]=S.getHours(),$[v+12>>>2>>>0]=S.getDate(),$[v+16>>>2>>>0]=S.getMonth(),$[v+20>>>2>>>0]=S.getYear(),v=S.getTime(),BigInt(isNaN(v)?-1:v/1e3)},U:function(){return-52},V:function(){},N:function(v,S,A,D){A>>>=0,D>>>=0;var V=new Date().getFullYear(),le=new Date(V,0,1),xe=new Date(V,6,1);V=le.getTimezoneOffset();var Ae=xe.getTimezoneOffset();L[v>>>0>>>2>>>0]=60*Math.max(V,Ae),$[S>>>0>>>2>>>0]=+(V!=Ae),v=Ke=>Ke.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],le=v(le),xe=v(xe),Ae{ke("")},d:function(v,S,A){return v>>>=0,S=kn(S>>>0,A>>>0),Ve[v](...S)},I:function(v,S,A){return v>>>=0,S=kn(S>>>0,A>>>0),Ve[v](...S)},H:()=>Date.now(),O:function(){return 4294901760},q:()=>performance.now(),M:function(v){v>>>=0;var S=Q.length;if(4294901760=A;A*=2){var D=S*(1+.2/A);D=Math.min(D,v+100663296);var V=Math;D=Math.max(v,D);e:{V=(V.min.call(V,4294901760,D+(65536-D%65536)%65536)-B.buffer.byteLength+65535)/65536;try{B.grow(V),W();var le=1;break e}catch{}le=void 0}if(le)return!0}return!1},$:function(v,S){v>>>=0,S>>>=0;var A=0;return ut().forEach((D,V)=>{var le=S+A;for(V=L[v+4*V>>>2>>>0]=le,le=0;le>>0]=D.charCodeAt(le);j[V>>>0]=0,A+=D.length+1}),0},aa:function(v,S){v>>>=0,S>>>=0;var A=ut();L[v>>>2>>>0]=A.length;var D=0;return A.forEach(V=>D+=V.length+1),L[S>>>2>>>0]=D,0},z:()=>52,F:function(){return 52},_:function(){return 70},E:function(v,S,A,D){S>>>=0,A>>>=0,D>>>=0;for(var V=0,le=0;le>>2>>>0],Ae=L[S+4>>>2>>>0];S+=8;for(var Ke=0;Ke>>0],st=tn[v];Ne===0||Ne===10?((v===1?I:C)(ne(st,0)),st.length=0):st.push(Ne)}V+=Ae}return L[D>>>2>>>0]=V,0},fa:wi,p:function(v,S,A,D){return wi(v>>>0,S>>>0,A>>>0,D>>>0)}},Qe=function(){function v(A){return Qe=A.exports,Qe=Fn(),Qe=$o(),B=Qe.ja,W(),Z.unshift(Qe.ka),ye--,ye==0&&Pe&&(A=Pe,Pe=null,A()),Qe}var S={a:Fi};if(ye++,a.instantiateWasm)try{return a.instantiateWasm(S,v)}catch(A){C(`Module.instantiateWasm callback failed with error: ${A}`),o(A)}return ot(S,function(A){v(A.instance)}).catch(o),{}}(),Jr=v=>(Jr=Qe.la)(v);a._OrtInit=(v,S)=>(a._OrtInit=Qe.ma)(v,S),a._OrtGetLastError=(v,S)=>(a._OrtGetLastError=Qe.na)(v,S),a._OrtCreateSessionOptions=(v,S,A,D,V,le,xe,Ae,Ke,Ne)=>(a._OrtCreateSessionOptions=Qe.oa)(v,S,A,D,V,le,xe,Ae,Ke,Ne),a._OrtAppendExecutionProvider=(v,S)=>(a._OrtAppendExecutionProvider=Qe.pa)(v,S),a._OrtAddFreeDimensionOverride=(v,S,A)=>(a._OrtAddFreeDimensionOverride=Qe.qa)(v,S,A),a._OrtAddSessionConfigEntry=(v,S,A)=>(a._OrtAddSessionConfigEntry=Qe.ra)(v,S,A),a._OrtReleaseSessionOptions=v=>(a._OrtReleaseSessionOptions=Qe.sa)(v),a._OrtCreateSession=(v,S,A)=>(a._OrtCreateSession=Qe.ta)(v,S,A),a._OrtReleaseSession=v=>(a._OrtReleaseSession=Qe.ua)(v),a._OrtGetInputOutputCount=(v,S,A)=>(a._OrtGetInputOutputCount=Qe.va)(v,S,A),a._OrtGetInputName=(v,S)=>(a._OrtGetInputName=Qe.wa)(v,S),a._OrtGetOutputName=(v,S)=>(a._OrtGetOutputName=Qe.xa)(v,S),a._OrtFree=v=>(a._OrtFree=Qe.ya)(v),a._OrtCreateTensor=(v,S,A,D,V,le)=>(a._OrtCreateTensor=Qe.za)(v,S,A,D,V,le),a._OrtGetTensorData=(v,S,A,D,V)=>(a._OrtGetTensorData=Qe.Aa)(v,S,A,D,V),a._OrtReleaseTensor=v=>(a._OrtReleaseTensor=Qe.Ba)(v),a._OrtCreateRunOptions=(v,S,A,D)=>(a._OrtCreateRunOptions=Qe.Ca)(v,S,A,D),a._OrtAddRunConfigEntry=(v,S,A)=>(a._OrtAddRunConfigEntry=Qe.Da)(v,S,A),a._OrtReleaseRunOptions=v=>(a._OrtReleaseRunOptions=Qe.Ea)(v),a._OrtCreateBinding=v=>(a._OrtCreateBinding=Qe.Fa)(v),a._OrtBindInput=(v,S,A)=>(a._OrtBindInput=Qe.Ga)(v,S,A),a._OrtBindOutput=(v,S,A,D)=>(a._OrtBindOutput=Qe.Ha)(v,S,A,D),a._OrtClearBoundOutputs=v=>(a._OrtClearBoundOutputs=Qe.Ia)(v),a._OrtReleaseBinding=v=>(a._OrtReleaseBinding=Qe.Ja)(v),a._OrtRunWithBinding=(v,S,A,D,V)=>(a._OrtRunWithBinding=Qe.Ka)(v,S,A,D,V),a._OrtRun=(v,S,A,D,V,le,xe,Ae)=>(a._OrtRun=Qe.La)(v,S,A,D,V,le,xe,Ae),a._OrtEndProfiling=v=>(a._OrtEndProfiling=Qe.Ma)(v),a._JsepOutput=(v,S,A)=>(a._JsepOutput=Qe.Na)(v,S,A),a._JsepGetNodeName=v=>(a._JsepGetNodeName=Qe.Oa)(v);var Gr=a._malloc=v=>(Gr=a._malloc=Qe.Pa)(v),xn=a._free=v=>(xn=a._free=Qe.Qa)(v),Ca=v=>(Ca=Qe.Sa)(v),$a=v=>($a=Qe.Ta)(v),xs=()=>(xs=Qe.Ua)(),Gi=v=>(Gi=Qe.Wa)(v),Co=()=>(Co=Qe.Xa)(),Sr=v=>(Sr=Qe.Ya)(v),ar=()=>(ar=Qe.Za)();a.___start_em_js=837952,a.___stop_em_js=838113;function $o(){var v=Qe;v=Object.assign({},v);var S=A=>D=>A(D)>>>0;return v.la=S(v.la),v.Pa=S(v.Pa),v.Ta=S(v.Ta),v.Ua=(A=>()=>A()>>>0)(v.Ua),v}a.stackSave=()=>xs(),a.stackRestore=v=>Ca(v),a.stackAlloc=v=>$a(v),a.UTF8ToString=ge,a.stringToUTF8=(v,S,A)=>_e(v,Q,S,A),a.lengthBytesUTF8=we;var ei;Pe=function v(){ei||Ss(),ei||(Pe=v)};function Ss(){if(!(0t)}),Z1=fs(()=>{}),Q1=fs(()=>{}),m0={};ms(m0,{cpus:()=>g0});var g0,J1=Ce(()=>{g0=void 0}),e2=fs((n,e)=>{var t=(()=>{var r=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(r||=__filename),function(i={}){function a(){return J.buffer!=de.buffer&&Fe(),de}function s(){return J.buffer!=de.buffer&&Fe(),ye}function o(){return J.buffer!=de.buffer&&Fe(),Pe}function l(){return J.buffer!=de.buffer&&Fe(),ke}function u(){return J.buffer!=de.buffer&&Fe(),Be}function c(){return J.buffer!=de.buffer&&Fe(),et}function h(){return J.buffer!=de.buffer&&Fe(),De}function p(){return J.buffer!=de.buffer&&Fe(),Xt}var d=i,m,y,g=new Promise((f,x)=>{m=f,y=x});d.mountExternalData=(f,x)=>{(d.Db||(d.Db=new Map)).set(f,x)},d.unmountExternalData=()=>{delete d.Db};let _=()=>{let f=(M,P,G)=>(...Y)=>{let me=ar,Me=P?.();Y=M(...Y);let Je=P?.();return Me!==Je&&(M=Je,G(Me),P=G=null),ar!=me?V():Y},x=M=>async(...P)=>{try{if(d.Cb)throw Error("Session already started");let G=d.Cb={ec:P[0],errors:[]},Y=await M(...P);if(d.Cb!==G)throw Error("Session mismatch");d.Kb?.flush();let me=G.errors;if(0Je),0d._OrtCreateSession,M=>d._OrtCreateSession=M),d._OrtRun=x(f(d._OrtRun,()=>d._OrtRun,M=>d._OrtRun=M)),d._OrtRunWithBinding=x(f(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,M=>d._OrtRunWithBinding=M)),d._OrtBindInput=f(d._OrtBindInput,()=>d._OrtBindInput,M=>d._OrtBindInput=M),_=void 0};d.jsepInit=(f,x)=>{if(_?.(),f==="webgpu"){[d.Kb,d.Wb,d.$b,d.Lb,d.Zb,d.ob,d.ac,d.cc,d.Xb,d.Yb,d.bc]=x;let M=d.Kb;d.jsepRegisterBuffer=(P,G,Y,me)=>M.registerBuffer(P,G,Y,me),d.jsepGetBuffer=P=>M.getBuffer(P),d.jsepCreateDownloader=(P,G,Y)=>M.createDownloader(P,G,Y),d.jsepOnReleaseSession=P=>{M.onReleaseSession(P)},d.jsepOnRunStart=P=>M.onRunStart(P)}};var w=Object.assign({},d),b="./this.program",E=(f,x)=>{throw x},T=typeof window=="object",I=typeof importScripts=="function",C=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",B=d.ENVIRONMENT_IS_PTHREAD||!1,R="";function k(f){return d.locateFile?d.locateFile(f,R):R+f}var j,Q,ie;if(C){var F=(h0(),la(yd)),$=(f0(),la(vd));R=I?$.dirname(R)+"/":__dirname+"/",j=(f,x)=>(f=_e(f)?new URL(f):$.normalize(f),F.readFileSync(f,x?void 0:"utf8")),ie=f=>(f=j(f,!0),f.buffer||(f=new Uint8Array(f)),f),Q=(f,x,M,P=!0)=>{f=_e(f)?new URL(f):$.normalize(f),F.readFile(f,P?void 0:"utf8",(G,Y)=>{G?M(G):x(P?Y.buffer:Y)})},!d.thisProgram&&1{throw process.exitCode=f,x},global.Worker=Z1().Worker}else(T||I)&&(I?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),typeof r<"u"&&r&&(R=r),R.startsWith("blob:")?R="":R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1),C||(j=f=>{var x=new XMLHttpRequest;return x.open("GET",f,!1),x.send(null),x.responseText},I&&(ie=f=>{var x=new XMLHttpRequest;return x.open("GET",f,!1),x.responseType="arraybuffer",x.send(null),new Uint8Array(x.response)}),Q=(f,x,M)=>{var P=new XMLHttpRequest;P.open("GET",f,!0),P.responseType="arraybuffer",P.onload=()=>{P.status==200||P.status==0&&P.response?x(P.response):M()},P.onerror=M,P.send(null)}));C&&typeof performance>"u"&&(global.performance=Q1().performance);var L=console.log.bind(console),H=console.error.bind(console);C&&(L=(...f)=>F.writeSync(1,f.join(" ")+` `),H=(...f)=>F.writeSync(2,f.join(" ")+` `));var K=L,X=H;Object.assign(d,w),w=null;var J,W,ae=!1,Z,de,ye,Pe,ke,Be,et,De,Xe,te,Xt;function Fe(){var f=J.buffer;d.HEAP8=de=new Int8Array(f),d.HEAP16=Pe=new Int16Array(f),d.HEAPU8=ye=new Uint8Array(f),d.HEAPU16=ke=new Uint16Array(f),d.HEAP32=Be=new Int32Array(f),d.HEAPU32=et=new Uint32Array(f),d.HEAPF32=De=new Float32Array(f),d.HEAPF64=Xt=new Float64Array(f),d.HEAP64=Xe=new BigInt64Array(f),d.HEAPU64=te=new BigUint64Array(f)}var ot=16777216;if(B)J=d.wasmMemory;else if(d.wasmMemory)J=d.wasmMemory;else if(J=new WebAssembly.Memory({initial:ot/65536,maximum:65536,shared:!0}),!(J.buffer instanceof SharedArrayBuffer))throw X("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),C&&X("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Fe(),ot=J.buffer.byteLength;var Ve=[],zt=[],xt=[],N=0,O=null;function ne(){if(N--,N==0&&O){var f=O;O=null,f()}}function ge(f){throw f="Aborted("+f+")",X(f),ae=!0,Z=1,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),y(f),f}var we=f=>f.startsWith("data:application/octet-stream;base64,"),_e=f=>f.startsWith("file://"),Ye;Ye="ort-wasm-simd-threaded.wasm",we(Ye)||(Ye=k(Ye));function Re(f){if(ie)return ie(f);throw"both async and sync fetching of the wasm failed"}function We(f){if(T||I){if(typeof fetch=="function"&&!_e(f))return fetch(f,{credentials:"same-origin"}).then(x=>{if(!x.ok)throw`failed to load wasm binary file at '${f}'`;return x.arrayBuffer()}).catch(()=>Re(f));if(Q)return new Promise((x,M)=>{Q(f,P=>x(new Uint8Array(P)),M)})}return Promise.resolve().then(()=>Re(f))}function nt(f,x,M){return We(f).then(P=>WebAssembly.instantiate(P,x)).then(M,P=>{X(`failed to asynchronously prepare wasm: ${P}`),ge(P)})}function dt(f,x){var M=Ye;return typeof WebAssembly.instantiateStreaming!="function"||we(M)||_e(M)||C||typeof fetch!="function"?nt(M,f,x):fetch(M,{credentials:"same-origin"}).then(P=>WebAssembly.instantiateStreaming(P,f).then(x,function(G){return X(`wasm streaming compile failed: ${G}`),X("falling back to ArrayBuffer instantiation"),nt(M,f,x)}))}var be={826468:(f,x,M,P)=>{if(typeof d>"u"||!d.Db)return 1;if(f=Rt(f>>>0),f.startsWith("./")&&(f=f.substring(2)),f=d.Db.get(f),!f)return 2;if(x>>>=0,M>>>=0,P>>>=0,x+M>f.byteLength)return 3;try{return s().set(f.subarray(x,x+M),P>>>0),0}catch{return 4}},826969:()=>{d.Xb()},827e3:()=>{d.Yb()},827029:()=>{d.bc()},827054:f=>d.Wb(f),827087:f=>d.$b(f),827119:(f,x,M)=>{d.Lb(f,x,M,!0)},827158:(f,x,M)=>{d.Lb(f,x,M)},827191:f=>{d.ob("Abs",f,void 0)},827242:f=>{d.ob("Neg",f,void 0)},827293:f=>{d.ob("Floor",f,void 0)},827346:f=>{d.ob("Ceil",f,void 0)},827398:f=>{d.ob("Reciprocal",f,void 0)},827456:f=>{d.ob("Sqrt",f,void 0)},827508:f=>{d.ob("Exp",f,void 0)},827559:f=>{d.ob("Erf",f,void 0)},827610:f=>{d.ob("Sigmoid",f,void 0)},827665:(f,x,M)=>{d.ob("HardSigmoid",f,{alpha:x,beta:M})},827744:f=>{d.ob("Log",f,void 0)},827795:f=>{d.ob("Sin",f,void 0)},827846:f=>{d.ob("Cos",f,void 0)},827897:f=>{d.ob("Tan",f,void 0)},827948:f=>{d.ob("Asin",f,void 0)},828e3:f=>{d.ob("Acos",f,void 0)},828052:f=>{d.ob("Atan",f,void 0)},828104:f=>{d.ob("Sinh",f,void 0)},828156:f=>{d.ob("Cosh",f,void 0)},828208:f=>{d.ob("Asinh",f,void 0)},828261:f=>{d.ob("Acosh",f,void 0)},828314:f=>{d.ob("Atanh",f,void 0)},828367:f=>{d.ob("Tanh",f,void 0)},828419:f=>{d.ob("Not",f,void 0)},828470:(f,x,M)=>{d.ob("Clip",f,{min:x,max:M})},828539:f=>{d.ob("Clip",f,void 0)},828591:(f,x)=>{d.ob("Elu",f,{alpha:x})},828649:f=>{d.ob("Relu",f,void 0)},828701:(f,x)=>{d.ob("LeakyRelu",f,{alpha:x})},828765:(f,x)=>{d.ob("ThresholdedRelu",f,{alpha:x})},828835:(f,x)=>{d.ob("Cast",f,{to:x})},828893:f=>{d.ob("Add",f,void 0)},828944:f=>{d.ob("Sub",f,void 0)},828995:f=>{d.ob("Mul",f,void 0)},829046:f=>{d.ob("Div",f,void 0)},829097:f=>{d.ob("Pow",f,void 0)},829148:f=>{d.ob("Equal",f,void 0)},829201:f=>{d.ob("Greater",f,void 0)},829256:f=>{d.ob("GreaterOrEqual",f,void 0)},829318:f=>{d.ob("Less",f,void 0)},829370:f=>{d.ob("LessOrEqual",f,void 0)},829429:(f,x,M,P,G)=>{d.ob("ReduceMean",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},829588:(f,x,M,P,G)=>{d.ob("ReduceMax",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},829746:(f,x,M,P,G)=>{d.ob("ReduceMin",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},829904:(f,x,M,P,G)=>{d.ob("ReduceProd",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},830063:(f,x,M,P,G)=>{d.ob("ReduceSum",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},830221:(f,x,M,P,G)=>{d.ob("ReduceL1",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},830378:(f,x,M,P,G)=>{d.ob("ReduceL2",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},830535:(f,x,M,P,G)=>{d.ob("ReduceLogSum",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},830696:(f,x,M,P,G)=>{d.ob("ReduceSumSquare",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},830860:(f,x,M,P,G)=>{d.ob("ReduceLogSumExp",f,{keepDims:!!x,noopWithEmptyAxes:!!M,axes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},831024:f=>{d.ob("Where",f,void 0)},831077:(f,x,M)=>{d.ob("Transpose",f,{perm:x?Array.from(u().subarray(x>>>0,M>>>0)):[]})},831185:(f,x,M,P)=>{d.ob("DepthToSpace",f,{blocksize:x,mode:Rt(M),format:P?"NHWC":"NCHW"})},831318:(f,x,M,P)=>{d.ob("DepthToSpace",f,{blocksize:x,mode:Rt(M),format:P?"NHWC":"NCHW"})},831451:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he,Tt)=>{d.ob("ConvTranspose",f,{format:Je?"NHWC":"NCHW",autoPad:x,dilations:[M],group:P,kernelShape:[G],pads:[Y,me],strides:[Me],wIsConst:()=>!!a()[Ge>>>0],outputPadding:pt?Array.from(u().subarray(pt>>>0,jt>>>0)):[],outputShape:Zt?Array.from(u().subarray(Zt>>>0,he>>>0)):[],activation:Rt(Tt)})},831852:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he)=>{d.ob("ConvTranspose",f,{format:Me?"NHWC":"NCHW",autoPad:x,dilations:Array.from(u().subarray(M>>>0,(M>>>0)+2>>>0)),group:P,kernelShape:Array.from(u().subarray(G>>>0,(G>>>0)+2>>>0)),pads:Array.from(u().subarray(Y>>>0,(Y>>>0)+4>>>0)),strides:Array.from(u().subarray(me>>>0,(me>>>0)+2>>>0)),wIsConst:()=>!!a()[Je>>>0],outputPadding:Ge?Array.from(u().subarray(Ge>>>0,pt>>>0)):[],outputShape:jt?Array.from(u().subarray(jt>>>0,Zt>>>0)):[],activation:Rt(he)})},832417:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he,Tt)=>{d.ob("ConvTranspose",f,{format:Je?"NHWC":"NCHW",autoPad:x,dilations:[M],group:P,kernelShape:[G],pads:[Y,me],strides:[Me],wIsConst:()=>!!a()[Ge>>>0],outputPadding:pt?Array.from(u().subarray(pt>>>0,jt>>>0)):[],outputShape:Zt?Array.from(u().subarray(Zt>>>0,he>>>0)):[],activation:Rt(Tt)})},832818:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he)=>{d.ob("ConvTranspose",f,{format:Me?"NHWC":"NCHW",autoPad:x,dilations:Array.from(u().subarray(M>>>0,(M>>>0)+2>>>0)),group:P,kernelShape:Array.from(u().subarray(G>>>0,(G>>>0)+2>>>0)),pads:Array.from(u().subarray(Y>>>0,(Y>>>0)+4>>>0)),strides:Array.from(u().subarray(me>>>0,(me>>>0)+2>>>0)),wIsConst:()=>!!a()[Je>>>0],outputPadding:Ge?Array.from(u().subarray(Ge>>>0,pt>>>0)):[],outputShape:jt?Array.from(u().subarray(jt>>>0,Zt>>>0)):[],activation:Rt(he)})},833383:(f,x)=>{d.ob("GlobalAveragePool",f,{format:x?"NHWC":"NCHW"})},833474:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he,Tt,Vt)=>{d.ob("AveragePool",f,{format:Vt?"NHWC":"NCHW",auto_pad:x,ceil_mode:M,count_include_pad:P,storage_order:G,dilations:[Y,me],kernel_shape:[Me,Je],pads:[Ge,pt,jt,Zt],strides:[he,Tt]})},833758:(f,x)=>{d.ob("GlobalAveragePool",f,{format:x?"NHWC":"NCHW"})},833849:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he,Tt,Vt)=>{d.ob("AveragePool",f,{format:Vt?"NHWC":"NCHW",auto_pad:x,ceil_mode:M,count_include_pad:P,storage_order:G,dilations:[Y,me],kernel_shape:[Me,Je],pads:[Ge,pt,jt,Zt],strides:[he,Tt]})},834133:(f,x)=>{d.ob("GlobalMaxPool",f,{format:x?"NHWC":"NCHW"})},834220:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he,Tt,Vt)=>{d.ob("MaxPool",f,{format:Vt?"NHWC":"NCHW",auto_pad:x,ceil_mode:M,count_include_pad:P,storage_order:G,dilations:[Y,me],kernel_shape:[Me,Je],pads:[Ge,pt,jt,Zt],strides:[he,Tt]})},834500:(f,x)=>{d.ob("GlobalMaxPool",f,{format:x?"NHWC":"NCHW"})},834587:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he,Tt,Vt)=>{d.ob("MaxPool",f,{format:Vt?"NHWC":"NCHW",auto_pad:x,ceil_mode:M,count_include_pad:P,storage_order:G,dilations:[Y,me],kernel_shape:[Me,Je],pads:[Ge,pt,jt,Zt],strides:[he,Tt]})},834867:(f,x,M,P,G)=>{d.ob("Gemm",f,{alpha:x,beta:M,transA:P,transB:G})},834971:f=>{d.ob("MatMul",f,void 0)},835025:(f,x,M,P)=>{d.ob("ArgMax",f,{keepDims:!!x,selectLastIndex:!!M,axis:P})},835133:(f,x,M,P)=>{d.ob("ArgMin",f,{keepDims:!!x,selectLastIndex:!!M,axis:P})},835241:(f,x)=>{d.ob("Softmax",f,{axis:x})},835304:(f,x)=>{d.ob("Concat",f,{axis:x})},835364:(f,x,M,P,G)=>{d.ob("Split",f,{axis:x,numOutputs:M,splitSizes:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},835504:f=>{d.ob("Expand",f,void 0)},835558:(f,x)=>{d.ob("Gather",f,{axis:Number(x)})},835629:(f,x)=>{d.ob("GatherElements",f,{axis:Number(x)})},835708:(f,x,M,P,G,Y,me,Me,Je,Ge,pt)=>{d.ob("Resize",f,{antialias:x,axes:M?Array.from(u().subarray(M>>>0,P>>>0)):[],coordinateTransformMode:Rt(G),cubicCoeffA:Y,excludeOutside:me,extrapolationValue:Me,keepAspectRatioPolicy:Rt(Je),mode:Rt(Ge),nearestMode:Rt(pt)})},836054:(f,x,M,P,G,Y,me)=>{d.ob("Slice",f,{starts:x?Array.from(u().subarray(x>>>0,M>>>0)):[],ends:P?Array.from(u().subarray(P>>>0,G>>>0)):[],axes:Y?Array.from(u().subarray(Y>>>0,me>>>0)):[]})},836270:f=>{d.ob("Tile",f,void 0)},836322:(f,x,M,P)=>{d.ob("LayerNormalization",f,{axis:x,epsilon:M,simplified:!!P})},836433:(f,x,M)=>{d.ob("InstanceNormalization",f,{epsilon:x,format:M?"NHWC":"NCHW"})},836547:(f,x,M)=>{d.ob("InstanceNormalization",f,{epsilon:x,format:M?"NHWC":"NCHW"})},836661:f=>{d.ob("Range",f,void 0)},836714:(f,x)=>{d.ob("Einsum",f,{equation:Rt(x)})},836795:(f,x,M,P,G)=>{d.ob("Pad",f,{mode:x,value:M,pads:P?Array.from(u().subarray(P>>>0,G>>>0)):[]})},836922:(f,x,M,P,G,Y)=>{d.ob("BatchNormalization",f,{epsilon:x,momentum:M,spatial:!!G,trainingMode:!!P,format:Y?"NHWC":"NCHW"})},837091:(f,x,M,P,G,Y)=>{d.ob("BatchNormalization",f,{epsilon:x,momentum:M,spatial:!!G,trainingMode:!!P,format:Y?"NHWC":"NCHW"})},837260:(f,x,M)=>{d.ob("CumSum",f,{exclusive:Number(x),reverse:Number(M)})},837357:(f,x,M,P,G,Y,me,Me,Je)=>{d.ob("Attention",f,{numHeads:x,isUnidirectional:M,maskFilterValue:P,scale:G,doRotary:Y,qkvHiddenSizes:me?Array.from(u().subarray(Number(Me)>>>0,Number(Me)+me>>>0)):[],pastPresentShareBuffer:!!Je})},837629:f=>{d.ob("BiasAdd",f,void 0)},837684:f=>{d.ob("BiasSplitGelu",f,void 0)},837745:f=>{d.ob("FastGelu",f,void 0)},837801:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt)=>{d.ob("Conv",f,{format:Je?"NHWC":"NCHW",auto_pad:x,dilations:[M],group:P,kernel_shape:[G],pads:Y?Array.from(u().subarray(Y>>>0,me>>>0)):[],strides:[Me],w_is_const:()=>!!a()[Ge>>>0],activation:Rt(pt),activation_params:jt?Array.from(h().subarray(jt>>>0,Zt>>>0)):[]})},838171:(f,x,M,P,G,Y,me,Me,Je,Ge,pt,jt,Zt,he,Tt,Vt)=>{d.ob("Conv",f,{format:jt?"NHWC":"NCHW",auto_pad:x,dilations:[M,P],group:G,kernel_shape:[Y,me],pads:Me?Array.from(u().subarray(Me>>>0,Je>>>0)):[],strides:[Ge,pt],w_is_const:()=>!!a()[Zt>>>0],activation:Rt(he),activation_params:Tt?Array.from(h().subarray(Tt>>>0,Vt>>>0)):[]})},838562:f=>{d.ob("Gelu",f,void 0)},838614:(f,x,M,P,G,Y)=>{d.ob("MatMulNBits",f,{k:x,n:M,accuracyLevel:P,bits:G,blockSize:Y})},838741:(f,x,M,P,G,Y)=>{d.ob("MultiHeadAttention",f,{numHeads:x,isUnidirectional:M,maskFilterValue:P,scale:G,doRotary:Y})},838900:(f,x,M,P,G)=>{d.ob("RotaryEmbedding",f,{interleaved:!!x,numHeads:M,rotaryEmbeddingDim:P,scale:G})},839039:(f,x,M)=>{d.ob("SkipLayerNormalization",f,{epsilon:x,simplified:!!M})},839141:(f,x,M)=>{d.ob("SkipLayerNormalization",f,{epsilon:x,simplified:!!M})},839243:(f,x,M,P)=>{d.ob("LayerNormalization",f,{axis:x,epsilon:M,simplified:!!P})},839354:f=>{d.ac(f)},839388:(f,x)=>d.cc(f,x,d.Cb.ec,d.Cb.errors)};function yt(f){this.name="ExitStatus",this.message=`Program terminated with exit(${f})`,this.status=f}var vt=f=>{f.terminate(),f.onmessage=()=>{}},ht=f=>{fe.xb.length==0&&(Se(),fe.Mb(fe.xb[0]));var x=fe.xb.pop();if(!x)return 6;fe.yb.push(x),fe.ub[f.wb]=x,x.wb=f.wb;var M={cmd:"run",start_routine:f.fc,arg:f.Rb,pthread_ptr:f.wb};return C&&x.unref(),x.postMessage(M,f.mc),0},Ue=0,Le=f=>{var x=Su();return f=f(),ko(x),f},U=(f,x,...M)=>Le(()=>{for(var P=2*M.length,G=xu(8*P),Y=G>>>3,me=0;me>>0]=Me)}return Th(f,0,P,G,x)});function ve(f){if(B)return U(0,1,f);Z=f,0{if(Z=f,B)throw lt(f),"unwind";ve(f)};function He(){for(var f=d.numThreads;f--;)Se();Ve.unshift(()=>{N++,q(()=>ne())})}function Se(){var f=k("ort-wasm-simd-threaded.worker.js");f=new Worker(f),fe.xb.push(f)}function q(f){B?f():Promise.all(fe.xb.map(fe.Mb)).then(f)}var fe={xb:[],yb:[],Qb:[],ub:{},Gb(){B?(fe.receiveObjectTransfer=fe.dc,fe.threadInitTLS=fe.Pb,fe.setExitStatus=fe.Ob):He()},Ob:f=>Z=f,pc:["$terminateWorker"],hc:()=>{for(var f of fe.yb)vt(f);for(f of fe.xb)vt(f);fe.xb=[],fe.yb=[],fe.ub=[]},Nb:f=>{var x=f.wb;delete fe.ub[x],fe.xb.push(f),fe.yb.splice(fe.yb.indexOf(f),1),f.wb=0,wu(x)},dc(){},Pb(){fe.Qb.forEach(f=>f())},Mb:f=>new Promise(x=>{f.onmessage=Y=>{Y=Y.data;var me=Y.cmd;if(Y.targetThread&&Y.targetThread!=Io()){var Me=fe.ub[Y.targetThread];Me?Me.postMessage(Y,Y.transferList):X(`Internal error! Worker sent a message "${me}" to target pthread ${Y.targetThread}, but that thread no longer exists!`)}else me==="checkMailbox"?xn():me==="spawnThread"?ht(Y):me==="cleanupThread"?fe.Nb(fe.ub[Y.thread]):me==="killThread"?(Y=Y.thread,me=fe.ub[Y],delete fe.ub[Y],vt(me),wu(Y),fe.yb.splice(fe.yb.indexOf(me),1),me.wb=0):me==="cancelThread"?fe.ub[Y.thread].postMessage({cmd:"cancel"}):me==="loaded"?(f.loaded=!0,C&&!f.wb&&f.unref(),x(f)):me==="alert"?alert(`Thread ${Y.threadId}: ${Y.text}`):Y.target==="setimmediate"?f.postMessage(Y):me==="callHandler"?d[Y.handler](...Y.args):me&&X(`worker sent an unknown command ${me}`)},f.onerror=Y=>{throw X(`worker sent an error! ${Y.filename}:${Y.lineno}: ${Y.message}`),Y},C&&(f.on("message",Y=>f.onmessage({data:Y})),f.on("error",Y=>f.onerror(Y)));var M=[],P=["onExit"],G;for(G of P)d.hasOwnProperty(G)&&M.push(G);f.postMessage({cmd:"load",handlers:M,urlOrBlob:d.mainScriptUrlOrBlob||r,wasmMemory:J,wasmModule:W})})};d.PThread=fe;var Ie=f=>{for(;0{var f=Io(),x=c()[f+52>>>2>>>0];f=c()[f+56>>>2>>>0],Ch(x,x-f),ko(x)};function lt(f){if(B)return U(1,0,f);Ze(f)}d.invokeEntryPoint=(f,x)=>{Ue=0,f=$h(f,x),0>>2>>>0]=0,c()[this.Ib+4>>>2>>>0]=x,c()[this.Ib+8>>>2>>>0]=M}}var Ct=0;function $t(f,x,M,P){return B?U(2,1,f,x,M,P):Yt(f,x,M,P)}function Yt(f,x,M,P){if(f>>>=0,x>>>=0,M>>>=0,P>>>=0,typeof SharedArrayBuffer>"u")return X("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return B&&G.length===0?$t(f,x,M,P):(f={fc:M,wb:f,Rb:P,mc:G},B?(f.oc="spawnThread",postMessage(f,G),0):ht(f))}var Jt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,It=(f,x,M)=>{x>>>=0;var P=x+M;for(M=x;f[M]&&!(M>=P);)++M;if(16G?P+=String.fromCharCode(G):(G-=65536,P+=String.fromCharCode(55296|G>>10,56320|G&1023))}}else P+=String.fromCharCode(G)}return P},Rt=(f,x)=>(f>>>=0)?It(s(),f,x):"";function Fn(f,x,M){return B?U(3,1,f,x,M):0}function Kn(f,x){if(B)return U(4,1,f,x)}var Pn=f=>{for(var x=0,M=0;M=P?x++:2047>=P?x+=2:55296<=P&&57343>=P?(x+=4,++M):x+=3}return x},Br=(f,x,M,P)=>{if(M>>>=0,!(0=me){var Me=f.charCodeAt(++Y);me=65536+((me&1023)<<10)|Me&1023}if(127>=me){if(M>=P)break;x[M++>>>0]=me}else{if(2047>=me){if(M+1>=P)break;x[M++>>>0]=192|me>>6}else{if(65535>=me){if(M+2>=P)break;x[M++>>>0]=224|me>>12}else{if(M+3>=P)break;x[M++>>>0]=240|me>>18,x[M++>>>0]=128|me>>12&63}x[M++>>>0]=128|me>>6&63}x[M++>>>0]=128|me&63}}return x[M>>>0]=0,M-G},Zn=(f,x,M)=>Br(f,s(),x,M);function Fr(f,x){if(B)return U(5,1,f,x)}function _i(f,x,M){if(B)return U(6,1,f,x,M)}function Bi(f,x,M){return B?U(7,1,f,x,M):0}function yi(f,x){if(B)return U(8,1,f,x)}function Ta(f,x,M){if(B)return U(9,1,f,x,M)}function Aa(f,x,M,P){if(B)return U(10,1,f,x,M,P)}function z(f,x,M,P){if(B)return U(11,1,f,x,M,P)}function ee(f,x,M,P){if(B)return U(12,1,f,x,M,P)}function oe(f){if(B)return U(13,1,f)}function ue(f,x){if(B)return U(14,1,f,x)}function se(f,x,M){if(B)return U(15,1,f,x,M)}var ze,qe=f=>{for(var x="";s()[f>>>0];)x+=ze[s()[f++>>>0]];return x},at={},ft={},mt;function wt(f,x,M={}){var P=x.name;if(!f)throw new mt(`type "${P}" must have a positive integer typeid pointer`);if(ft.hasOwnProperty(f)){if(M.Ub)return;throw new mt(`Cannot register type '${P}' twice`)}ft[f]=x,at.hasOwnProperty(f)&&(x=at[f],delete at[f],x.forEach(G=>G()))}function rt(f,x,M={}){if(!("argPackAdvance"in x))throw new TypeError("registerType registeredInstance requires argPackAdvance");return wt(f,x,M)}var en=(f,x,M)=>{switch(x){case 1:return M?P=>a()[P>>>0]:P=>s()[P>>>0];case 2:return M?P=>o()[P>>>1>>>0]:P=>l()[P>>>1>>>0];case 4:return M?P=>u()[P>>>2>>>0]:P=>c()[P>>>2>>>0];case 8:return M?P=>Xe[P>>>3]:P=>te[P>>>3];default:throw new TypeError(`invalid integer width (${x}): ${f}`)}},gn=[],Wt=[];function kn(f){f>>>=0,9{if(!f)throw new mt("Cannot use deleted val. handle = "+f);return Wt[f]},ut=f=>{switch(f){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let x=gn.pop()||Wt.length;return Wt[x]=f,Wt[x+1]=1,x}};function xr(f){return this.fromWireType(c()[f>>>2>>>0])}var tn={name:"emscripten::val",fromWireType:f=>{var x=Mt(f);return kn(f),x},toWireType:(f,x)=>ut(x),argPackAdvance:8,readValueFromPointer:xr,Bb:null},cr=(f,x)=>{switch(x){case 4:return function(M){return this.fromWireType(h()[M>>>2>>>0])};case 8:return function(M){return this.fromWireType(p()[M>>>3>>>0])};default:throw new TypeError(`invalid float width (${x}): ${f}`)}},vi=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Qr=(f,x)=>{for(var M=f>>1,P=M+x/2;!(M>=P)&&l()[M>>>0];)++M;if(M<<=1,32=x/2);++P){var G=o()[f+2*P>>>1>>>0];if(G==0)break;M+=String.fromCharCode(G)}return M},wi=(f,x,M)=>{if(M??=2147483647,2>M)return 0;M-=2;var P=x;M=M<2*f.length?M/2:f.length;for(var G=0;G>>1>>>0]=Y,x+=2}return o()[x>>>1>>>0]=0,x-P},hn=f=>2*f.length,Qn=(f,x)=>{for(var M=0,P="";!(M>=x/4);){var G=u()[f+4*M>>>2>>>0];if(G==0)break;++M,65536<=G?(G-=65536,P+=String.fromCharCode(55296|G>>10,56320|G&1023)):P+=String.fromCharCode(G)}return P},Fi=(f,x,M)=>{if(x>>>=0,M??=2147483647,4>M)return 0;var P=x;M=P+M-4;for(var G=0;G=Y){var me=f.charCodeAt(++G);Y=65536+((Y&1023)<<10)|me&1023}if(u()[x>>>2>>>0]=Y,x+=4,x+4>M)break}return u()[x>>>2>>>0]=0,x-P},Qe=f=>{for(var x=0,M=0;M=P&&++M,x+=4}return x},Jr=f=>{if(!ae)try{if(f(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(u(),f>>>2,f).value.then(xn),f+=128,Atomics.store(u(),f>>>2,1))}d.__emscripten_thread_mailbox_await=Gr;var xn=()=>{var f=Io();f&&(Gr(f),Jr(Ah))};d.checkMailbox=xn;var Ca=[],$a=(f,x)=>{var M=ft[f];if(M===void 0)throw f=Eh(f),M=qe(f),Wr(f),new mt(`${x} has unknown type ${M}`);return M},xs=(f,x,M)=>{var P=[];return f=f.toWireType(P,M),P.length&&(c()[x>>>2>>>0]=ut(P)),f},Gi=f=>{try{f()}catch(x){ge(x)}};function Co(){var f=tt,x={};for(let[M,P]of Object.entries(f))x[M]=typeof P=="function"?(...G)=>{ei.push(M);try{return P(...G)}finally{ae||(ei.pop(),ar&&Sr===1&&ei.length===0&&(Sr=0,Ue+=1,Gi(Ih),typeof Fibers<"u"&&Fibers.rc()))}}:P;return x}var Sr=0,ar=null,$o=0,ei=[],Ss={},v={},S=0,A=null,D=[];function V(){return new Promise((f,x)=>{A={resolve:f,reject:x}})}function le(){var f=Po(65548),x=f+12;c()[f>>>2>>>0]=x,c()[f+4>>>2>>>0]=x+65536,x=ei[0];var M=Ss[x];return M===void 0&&(M=S++,Ss[x]=M,v[M]=x),x=M,u()[f+8>>>2>>>0]=x,f}function xe(){var f=u()[ar+8>>>2>>>0];return f=tt[v[f]],--Ue,f()}function Ae(f){if(!ae){if(Sr===0){var x=!1,M=!1;f((P=0)=>{if(!ae&&($o=P,x=!0,M)){Sr=2,Gi(()=>Ph(ar)),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.resume(),P=!1;try{var G=xe()}catch(Me){G=Me,P=!0}var Y=!1;if(!ar){var me=A;me&&(A=null,(P?me.reject:me.resolve)(G),Y=!0)}if(P&&!Y)throw G}}),M=!0,x||(Sr=1,ar=le(),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.pause(),Gi(()=>Rh(ar)))}else Sr===2?(Sr=0,Gi(kh),Wr(ar),ar=null,D.forEach(Jr)):ge(`invalid state: ${Sr}`);return $o}}function Ke(f){return Ae(x=>{f().then(x)})}var Ne=[],st={},Bt=f=>{var x=st[f];return x===void 0?qe(f):x},Ht=()=>typeof globalThis=="object"?globalThis:Function("return this")(),ce=f=>{var x=Ne.length;return Ne.push(f),x},St=(f,x)=>{for(var M=Array(f),P=0;P>>2>>>0],"parameter "+P);return M},Ut=(f,x)=>Object.defineProperty(x,"name",{value:f});function ti(f){var x=Function;if(!(x instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof x} which is not a function`);var M=Ut(x.name||"unknownFunctionName",function(){});return M.prototype=x.prototype,M=new M,f=x.apply(M,f),f instanceof Object?f:M}var ni=f=>f%4===0&&(f%100!==0||f%400===0),lh=[0,31,60,91,121,152,182,213,244,274,305,335],uh=[0,31,59,90,120,151,181,212,243,273,304,334];function ch(f,x,M,P,G,Y,me){return B?U(16,1,f,x,M,P,G,Y,me):-52}function dh(f,x,M,P,G,Y){if(B)return U(17,1,f,x,M,P,G,Y)}var _u=[],hh=(f,x)=>{_u.length=0;for(var M;M=s()[f++>>>0];){var P=M!=105;P&=M!=112,x+=P&&x%8?4:0,_u.push(M==112?c()[x>>>2>>>0]:M==106?Xe[x>>>3]:M==105?u()[x>>>2>>>0]:p()[x>>>3>>>0]),x+=P?8:4}return _u},yu={},ph=()=>{if(!vu){var f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:b||"./this.program"},x;for(x in yu)yu[x]===void 0?delete f[x]:f[x]=yu[x];var M=[];for(x in f)M.push(`${x}=${f[x]}`);vu=M}return vu},vu;function fh(f,x){if(B)return U(18,1,f,x);f>>>=0,x>>>=0;var M=0;return ph().forEach((P,G)=>{var Y=x+M;for(G=c()[f+4*G>>>2>>>0]=Y,Y=0;Y>>0]=P.charCodeAt(Y);a()[G>>>0]=0,M+=P.length+1}),0}function mh(f,x){if(B)return U(19,1,f,x);f>>>=0,x>>>=0;var M=ph();c()[f>>>2>>>0]=M.length;var P=0;return M.forEach(G=>P+=G.length+1),c()[x>>>2>>>0]=P,0}function gh(f){return B?U(20,1,f):52}function _h(f,x,M,P){return B?U(21,1,f,x,M,P):52}function yh(f,x,M,P){return B?U(22,1,f,x,M,P):70}var i1=[null,[],[]];function vh(f,x,M,P){if(B)return U(23,1,f,x,M,P);x>>>=0,M>>>=0,P>>>=0;for(var G=0,Y=0;Y>>2>>>0],Me=c()[x+4>>>2>>>0];x+=8;for(var Je=0;Je>>0],pt=i1[f];Ge===0||Ge===10?((f===1?K:X)(It(pt,0)),pt.length=0):pt.push(Ge)}G+=Me}return c()[P>>>2>>>0]=G,0}var wh=[31,29,31,30,31,30,31,31,30,31,30,31],bh=[31,28,31,30,31,30,31,31,30,31,30,31];function a1(f){var x=Array(Pn(f)+1);return Br(f,x,0,x.length),x}var s1=(f,x)=>{a().set(f,x>>>0)};function xh(f,x,M,P){function G(he,Tt,Vt){for(he=typeof he=="number"?he.toString():he||"";he.lengthDh?-1:0Wi-he.getDate())Tt-=Wi-he.getDate()+1,he.setDate(1),11>Vt?he.setMonth(Vt+1):(he.setMonth(0),he.setFullYear(he.getFullYear()+1));else{he.setDate(he.getDate()+Tt);break}}return Vt=new Date(he.getFullYear()+1,0,4),Tt=Me(new Date(he.getFullYear(),0,4)),Vt=Me(Vt),0>=me(Tt,he)?0>=me(Vt,he)?he.getFullYear()+1:he.getFullYear():he.getFullYear()-1}f>>>=0,x>>>=0,M>>>=0,P>>>=0;var Ge=c()[P+40>>>2>>>0];P={kc:u()[P>>>2>>>0],jc:u()[P+4>>>2>>>0],Eb:u()[P+8>>>2>>>0],Jb:u()[P+12>>>2>>>0],Fb:u()[P+16>>>2>>>0],Ab:u()[P+20>>>2>>>0],vb:u()[P+24>>>2>>>0],zb:u()[P+28>>>2>>>0],qc:u()[P+32>>>2>>>0],ic:u()[P+36>>>2>>>0],lc:Ge?Rt(Ge):""},M=Rt(M),Ge={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var pt in Ge)M=M.replace(new RegExp(pt,"g"),Ge[pt]);var jt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Zt="January February March April May June July August September October November December".split(" ");Ge={"%a":he=>jt[he.vb].substring(0,3),"%A":he=>jt[he.vb],"%b":he=>Zt[he.Fb].substring(0,3),"%B":he=>Zt[he.Fb],"%C":he=>Y((he.Ab+1900)/100|0,2),"%d":he=>Y(he.Jb,2),"%e":he=>G(he.Jb,2," "),"%g":he=>Je(he).toString().substring(2),"%G":Je,"%H":he=>Y(he.Eb,2),"%I":he=>(he=he.Eb,he==0?he=12:12{for(var Tt=0,Vt=0;Vt<=he.Fb-1;Tt+=(ni(he.Ab+1900)?wh:bh)[Vt++]);return Y(he.Jb+Tt,3)},"%m":he=>Y(he.Fb+1,2),"%M":he=>Y(he.jc,2),"%n":()=>` `,"%p":he=>0<=he.Eb&&12>he.Eb?"AM":"PM","%S":he=>Y(he.kc,2),"%t":()=>" ","%u":he=>he.vb||7,"%U":he=>Y(Math.floor((he.zb+7-he.vb)/7),2),"%V":he=>{var Tt=Math.floor((he.zb+7-(he.vb+6)%7)/7);if(2>=(he.vb+371-he.zb-2)%7&&Tt++,Tt)Tt==53&&(Vt=(he.vb+371-he.zb)%7,Vt==4||Vt==3&&ni(he.Ab)||(Tt=1));else{Tt=52;var Vt=(he.vb+7-he.zb-1)%7;(Vt==4||Vt==5&&ni(he.Ab%400-1))&&Tt++}return Y(Tt,2)},"%w":he=>he.vb,"%W":he=>Y(Math.floor((he.zb+7-(he.vb+6)%7)/7),2),"%y":he=>(he.Ab+1900).toString().substring(2),"%Y":he=>he.Ab+1900,"%z":he=>{he=he.ic;var Tt=0<=he;return he=Math.abs(he)/60,(Tt?"+":"-")+("0000"+(he/60*100+he%60)).slice(-4)},"%Z":he=>he.lc,"%%":()=>"%"},M=M.replace(/%%/g,"\0\0");for(pt in Ge)M.includes(pt)&&(M=M.replace(new RegExp(pt,"g"),Ge[pt](P)));return M=M.replace(/\0\0/g,"%"),pt=a1(M),pt.length>x?0:(s1(pt,f),pt.length-1)}fe.Gb();for(var Sh=Array(256),Ro=0;256>Ro;++Ro)Sh[Ro]=String.fromCharCode(Ro);ze=Sh,mt=d.BindingError=class extends Error{constructor(f){super(f),this.name="BindingError"}},d.InternalError=class extends Error{constructor(f){super(f),this.name="InternalError"}},Wt.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>Wt.length/2-5-gn.length;var o1=[ve,lt,$t,Fn,Kn,Fr,_i,Bi,yi,Ta,Aa,z,ee,oe,ue,se,ch,dh,fh,mh,gh,_h,yh,vh],l1={ua:function(f,x,M){return Ke(async()=>{await d.Zb(f,x,M)})},b:function(f,x,M){throw f>>>=0,new it(f).Gb(x>>>0,M>>>0),Ct=f,Ct},ia:function(f){Mh(f>>>0,!I,1,!T,131072,!1),fe.Pb()},G:function(f){f>>>=0,B?postMessage({cmd:"cleanupThread",thread:f}):fe.Nb(fe.ub[f])},_:Yt,A:Fn,pa:Kn,W:Fr,Y:_i,qa:Bi,na:yi,fa:Ta,ma:Aa,K:z,X:ee,U:oe,oa:ue,V:se,E:function(f,x,M){f>>>=0,M>>>=0,x=qe(x>>>0),rt(f,{name:x,fromWireType:P=>P,toWireType:function(P,G){if(typeof G!="bigint"&&typeof G!="number")throw G===null?G="null":(P=typeof G,G=P==="object"||P==="array"||P==="function"?G.toString():""+G),new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:8,readValueFromPointer:en(x,M,x.indexOf("u")==-1),Bb:null})},O:function(f,x,M,P){f>>>=0,x=qe(x>>>0),rt(f,{name:x,fromWireType:function(G){return!!G},toWireType:function(G,Y){return Y?M:P},argPackAdvance:8,readValueFromPointer:function(G){return this.fromWireType(s()[G>>>0])},Bb:null})},N:function(f){return rt(f>>>0,tn)},D:function(f,x,M){f>>>=0,M>>>=0,x=qe(x>>>0),rt(f,{name:x,fromWireType:P=>P,toWireType:(P,G)=>G,argPackAdvance:8,readValueFromPointer:cr(x,M),Bb:null})},t:function(f,x,M,P,G){if(f>>>=0,M>>>=0,x=qe(x>>>0),G===-1&&(G=4294967295),G=Me=>Me,P===0){var Y=32-8*M;G=Me=>Me<>>Y}var me=x.includes("unsigned")?function(Me,Je){return Je>>>0}:function(Me,Je){return Je};rt(f,{name:x,fromWireType:G,toWireType:me,argPackAdvance:8,readValueFromPointer:en(x,M,P!==0),Bb:null})},p:function(f,x,M){function P(Y){var me=c()[Y>>>2>>>0];return Y=c()[Y+4>>>2>>>0],new G(a().buffer,Y,me)}f>>>=0;var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][x];M=qe(M>>>0),rt(f,{name:M,fromWireType:P,argPackAdvance:8,readValueFromPointer:P},{Ub:!0})},F:function(f,x){f>>>=0,x=qe(x>>>0);var M=x==="std::string";rt(f,{name:x,fromWireType:function(P){var G=c()[P>>>2>>>0],Y=P+4;if(M)for(var me=Y,Me=0;Me<=G;++Me){var Je=Y+Me;if(Me==G||s()[Je>>>0]==0){if(me=Rt(me,Je-me),Ge===void 0)var Ge=me;else Ge+="\0",Ge+=me;me=Je+1}}else{for(Ge=Array(G),Me=0;Me>>0]);Ge=Ge.join("")}return Wr(P),Ge},toWireType:function(P,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var Y=typeof G=="string";if(!(Y||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new mt("Cannot pass non-string to std::string");var me=M&&Y?Pn(G):G.length,Me=Po(4+me+1),Je=Me+4;if(c()[Me>>>2>>>0]=me,M&&Y)Zn(G,Je,me+1);else if(Y)for(Y=0;Y>>0]=Ge}else for(Y=0;Y>>0]=G[Y];return P!==null&&P.push(Wr,Me),Me},argPackAdvance:8,readValueFromPointer:xr,Bb(P){Wr(P)}})},z:function(f,x,M){if(f>>>=0,x>>>=0,M>>>=0,M=qe(M),x===2)var P=Qr,G=wi,Y=hn,me=Me=>l()[Me>>>1>>>0];else x===4&&(P=Qn,G=Fi,Y=Qe,me=Me=>c()[Me>>>2>>>0]);rt(f,{name:M,fromWireType:Me=>{for(var Je=c()[Me>>>2>>>0],Ge,pt=Me+4,jt=0;jt<=Je;++jt){var Zt=Me+4+jt*x;(jt==Je||me(Zt)==0)&&(pt=P(pt,Zt-pt),Ge===void 0?Ge=pt:(Ge+="\0",Ge+=pt),pt=Zt+x)}return Wr(Me),Ge},toWireType:(Me,Je)=>{if(typeof Je!="string")throw new mt(`Cannot pass non-string to C++ string type ${M}`);var Ge=Y(Je),pt=Po(4+Ge+x);return c()[pt>>>2>>>0]=Ge/x,G(Je,pt+4,Ge+x),Me!==null&&Me.push(Wr,pt),pt},argPackAdvance:8,readValueFromPointer:xr,Bb(Me){Wr(Me)}})},P:function(f,x){f>>>=0,x=qe(x>>>0),rt(f,{Vb:!0,name:x,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ta:()=>1,S:function(f,x){f>>>=0,f==x>>>0?setTimeout(xn):B?postMessage({targetThread:f,cmd:"checkMailbox"}):(f=fe.ub[f])&&f.postMessage({cmd:"checkMailbox"})},$:function(f,x,M,P,G){x>>>=0,M>>>=0,P/=2,Ca.length=P,G=G>>>0>>>3;for(var Y=0;Y>>0];return f=x?be[x]:o1[f],fe.Sb=M,M=f(...Ca),fe.Sb=0,M},ha:Gr,sa:function(f){C&&fe.ub[f>>>0].ref()},w:function(f,x,M){return x>>>=0,M>>>=0,f=Mt(f>>>0),x=$a(x,"emval::as"),xs(x,M,f)},y:function(f){return f>>>=0,Ke(()=>(f=Mt(f),f.then(ut)))},o:function(f,x,M,P){return M>>>=0,P>>>=0,f=Ne[f>>>0],x=Mt(x>>>0),f(null,x,M,P)},k:function(f,x,M,P,G){return M>>>=0,P>>>=0,G>>>=0,f=Ne[f>>>0],x=Mt(x>>>0),M=Bt(M),f(x,x[M],P,G)},c:kn,C:function(f,x){return x>>>=0,f=Mt(f>>>0),x=Mt(x),f==x},n:function(f){return f>>>=0,f===0?ut(Ht()):(f=Bt(f),ut(Ht()[f]))},j:function(f,x,M){x=St(f,x>>>0);var P=x.shift();f--;var G=`return function (obj, func, destructorsRef, args) { `,Y=0,me=[];M===0&&me.push("obj");for(var Me=["retType"],Je=[P],Ge=0;Gept.name).join(", ")}) => ${P.name}>`,ce(Ut(M,f))},s:function(f,x){return x>>>=0,f=Mt(f>>>0),x=Mt(x),ut(f[x])},d:function(f){f>>>=0,9>>0);for(var x=Array(f.length),M=0;M>>0))},l:function(){return ut({})},i:function(f){f>>>=0;for(var x=Mt(f);x.length;){var M=x.pop();x.pop()(M)}kn(f)},h:function(f,x,M){x>>>=0,M>>>=0,f=Mt(f>>>0),x=Mt(x),M=Mt(M),f[x]=M},e:function(f,x){return x>>>=0,f=$a(f>>>0,"_emval_take_value"),f=f.readValueFromPointer(x),ut(f)},ca:function(f,x){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),u()[x>>>2>>>0]=f.getUTCSeconds(),u()[x+4>>>2>>>0]=f.getUTCMinutes(),u()[x+8>>>2>>>0]=f.getUTCHours(),u()[x+12>>>2>>>0]=f.getUTCDate(),u()[x+16>>>2>>>0]=f.getUTCMonth(),u()[x+20>>>2>>>0]=f.getUTCFullYear()-1900,u()[x+24>>>2>>>0]=f.getUTCDay(),f=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,u()[x+28>>>2>>>0]=f},da:function(f,x){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),u()[x>>>2>>>0]=f.getSeconds(),u()[x+4>>>2>>>0]=f.getMinutes(),u()[x+8>>>2>>>0]=f.getHours(),u()[x+12>>>2>>>0]=f.getDate(),u()[x+16>>>2>>>0]=f.getMonth(),u()[x+20>>>2>>>0]=f.getFullYear()-1900,u()[x+24>>>2>>>0]=f.getDay();var M=(ni(f.getFullYear())?lh:uh)[f.getMonth()]+f.getDate()-1|0;u()[x+28>>>2>>>0]=M,u()[x+36>>>2>>>0]=-(60*f.getTimezoneOffset()),M=new Date(f.getFullYear(),6,1).getTimezoneOffset();var P=new Date(f.getFullYear(),0,1).getTimezoneOffset();f=(M!=P&&f.getTimezoneOffset()==Math.min(P,M))|0,u()[x+32>>>2>>>0]=f},ea:function(f){f>>>=0;var x=new Date(u()[f+20>>>2>>>0]+1900,u()[f+16>>>2>>>0],u()[f+12>>>2>>>0],u()[f+8>>>2>>>0],u()[f+4>>>2>>>0],u()[f>>>2>>>0],0),M=u()[f+32>>>2>>>0],P=x.getTimezoneOffset(),G=new Date(x.getFullYear(),6,1).getTimezoneOffset(),Y=new Date(x.getFullYear(),0,1).getTimezoneOffset(),me=Math.min(Y,G);return 0>M?u()[f+32>>>2>>>0]=+(G!=Y&&me==P):0>>2>>>0]=x.getDay(),M=(ni(x.getFullYear())?lh:uh)[x.getMonth()]+x.getDate()-1|0,u()[f+28>>>2>>>0]=M,u()[f>>>2>>>0]=x.getSeconds(),u()[f+4>>>2>>>0]=x.getMinutes(),u()[f+8>>>2>>>0]=x.getHours(),u()[f+12>>>2>>>0]=x.getDate(),u()[f+16>>>2>>>0]=x.getMonth(),u()[f+20>>>2>>>0]=x.getYear(),f=x.getTime(),BigInt(isNaN(f)?-1:f/1e3)},aa:ch,ba:dh,R:function(f,x,M,P){f>>>=0,x>>>=0,M>>>=0,P>>>=0;var G=new Date().getFullYear(),Y=new Date(G,0,1),me=new Date(G,6,1);G=Y.getTimezoneOffset();var Me=me.getTimezoneOffset(),Je=Math.max(G,Me);c()[f>>>2>>>0]=60*Je,u()[x>>>2>>>0]=+(G!=Me),f=Ge=>Ge.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],Y=f(Y),me=f(me),Me{ge("")},f:function(f,x,M){return f>>>=0,x=hh(x>>>0,M>>>0),be[f](...x)},M:function(f,x,M){return f>>>=0,x=hh(x>>>0,M>>>0),be[f](...x)},H:()=>{},L:()=>Date.now(),ra:()=>{throw Ue+=1,"unwind"},T:function(){return 4294901760},u:()=>performance.timeOrigin+performance.now(),x:()=>C?(J1(),la(m0)).cpus().length:navigator.hardwareConcurrency,Q:function(f){f>>>=0;var x=s().length;if(f<=x||4294901760=M;M*=2){var P=x*(1+.2/M);P=Math.min(P,f+100663296);var G=Math;P=Math.max(f,P);e:{G=(G.min.call(G,4294901760,P+(65536-P%65536)%65536)-J.buffer.byteLength+65535)/65536;try{J.grow(G),Fe();var Y=1;break e}catch{}Y=void 0}if(Y)return!0}return!1},ja:fh,la:mh,Z:Ze,B:gh,J:_h,ga:yh,I:vh,a:J||d.wasmMemory,ka:xh,r:function(f,x,M,P){return xh(f>>>0,x>>>0,M>>>0,P>>>0)}},tt=function(){function f(M,P){return tt=M.exports,tt=Co(),tt=u1(),fe.Qb.push(tt.cb),zt.unshift(tt.va),W=P,ne(),tt}var x={a:l1};if(N++,d.instantiateWasm)try{return d.instantiateWasm(x,f)}catch(M){X(`Module.instantiateWasm callback failed with error: ${M}`),y(M)}return dt(x,function(M){f(M.instance,M.module)}).catch(y),{}}(),Eh=f=>(Eh=tt.wa)(f);d.__embind_initialize_bindings=()=>(d.__embind_initialize_bindings=tt.xa)(),d._OrtInit=(f,x)=>(d._OrtInit=tt.ya)(f,x),d._OrtGetLastError=(f,x)=>(d._OrtGetLastError=tt.za)(f,x),d._OrtCreateSessionOptions=(f,x,M,P,G,Y,me,Me,Je,Ge)=>(d._OrtCreateSessionOptions=tt.Aa)(f,x,M,P,G,Y,me,Me,Je,Ge),d._OrtAppendExecutionProvider=(f,x)=>(d._OrtAppendExecutionProvider=tt.Ba)(f,x),d._OrtAddFreeDimensionOverride=(f,x,M)=>(d._OrtAddFreeDimensionOverride=tt.Ca)(f,x,M),d._OrtAddSessionConfigEntry=(f,x,M)=>(d._OrtAddSessionConfigEntry=tt.Da)(f,x,M),d._OrtReleaseSessionOptions=f=>(d._OrtReleaseSessionOptions=tt.Ea)(f),d._OrtCreateSession=(f,x,M)=>(d._OrtCreateSession=tt.Fa)(f,x,M),d._OrtReleaseSession=f=>(d._OrtReleaseSession=tt.Ga)(f),d._OrtGetInputOutputCount=(f,x,M)=>(d._OrtGetInputOutputCount=tt.Ha)(f,x,M),d._OrtGetInputName=(f,x)=>(d._OrtGetInputName=tt.Ia)(f,x),d._OrtGetOutputName=(f,x)=>(d._OrtGetOutputName=tt.Ja)(f,x),d._OrtFree=f=>(d._OrtFree=tt.Ka)(f),d._OrtCreateTensor=(f,x,M,P,G,Y)=>(d._OrtCreateTensor=tt.La)(f,x,M,P,G,Y),d._OrtGetTensorData=(f,x,M,P,G)=>(d._OrtGetTensorData=tt.Ma)(f,x,M,P,G),d._OrtReleaseTensor=f=>(d._OrtReleaseTensor=tt.Na)(f),d._OrtCreateRunOptions=(f,x,M,P)=>(d._OrtCreateRunOptions=tt.Oa)(f,x,M,P),d._OrtAddRunConfigEntry=(f,x,M)=>(d._OrtAddRunConfigEntry=tt.Pa)(f,x,M),d._OrtReleaseRunOptions=f=>(d._OrtReleaseRunOptions=tt.Qa)(f),d._OrtCreateBinding=f=>(d._OrtCreateBinding=tt.Ra)(f),d._OrtBindInput=(f,x,M)=>(d._OrtBindInput=tt.Sa)(f,x,M),d._OrtBindOutput=(f,x,M,P)=>(d._OrtBindOutput=tt.Ta)(f,x,M,P),d._OrtClearBoundOutputs=f=>(d._OrtClearBoundOutputs=tt.Ua)(f),d._OrtReleaseBinding=f=>(d._OrtReleaseBinding=tt.Va)(f),d._OrtRunWithBinding=(f,x,M,P,G)=>(d._OrtRunWithBinding=tt.Wa)(f,x,M,P,G),d._OrtRun=(f,x,M,P,G,Y,me,Me)=>(d._OrtRun=tt.Xa)(f,x,M,P,G,Y,me,Me),d._OrtEndProfiling=f=>(d._OrtEndProfiling=tt.Ya)(f),d._JsepOutput=(f,x,M)=>(d._JsepOutput=tt.Za)(f,x,M),d._JsepGetNodeName=f=>(d._JsepGetNodeName=tt._a)(f);var Io=d._pthread_self=()=>(Io=d._pthread_self=tt.$a)(),Po=d._malloc=f=>(Po=d._malloc=tt.ab)(f),Wr=d._free=f=>(Wr=d._free=tt.bb)(f);d.__emscripten_tls_init=()=>(d.__emscripten_tls_init=tt.cb)();var Mh=d.__emscripten_thread_init=(f,x,M,P,G,Y)=>(Mh=d.__emscripten_thread_init=tt.eb)(f,x,M,P,G,Y);d.__emscripten_thread_crashed=()=>(d.__emscripten_thread_crashed=tt.fb)();var Th=(f,x,M,P,G)=>(Th=tt.gb)(f,x,M,P,G),wu=f=>(wu=tt.hb)(f),bu=d.__emscripten_thread_exit=f=>(bu=d.__emscripten_thread_exit=tt.ib)(f),Ah=()=>(Ah=tt.jb)(),Ch=(f,x)=>(Ch=tt.kb)(f,x),ko=f=>(ko=tt.lb)(f),xu=f=>(xu=tt.mb)(f),Su=()=>(Su=tt.nb)(),$h=d.dynCall_ii=(f,x)=>($h=d.dynCall_ii=tt.pb)(f,x),Rh=f=>(Rh=tt.qb)(f),Ih=()=>(Ih=tt.rb)(),Ph=f=>(Ph=tt.sb)(f),kh=()=>(kh=tt.tb)();d.___start_em_js=839500,d.___stop_em_js=839661;function u1(){var f=tt;f=Object.assign({},f);var x=P=>G=>P(G)>>>0,M=P=>()=>P()>>>0;return f.wa=x(f.wa),f.$a=M(f.$a),f.ab=x(f.ab),f.emscripten_main_runtime_thread_id=M(f.emscripten_main_runtime_thread_id),f.mb=x(f.mb),f.nb=M(f.nb),f}d.wasmMemory=J,d.stackSave=()=>Su(),d.stackRestore=f=>ko(f),d.stackAlloc=f=>xu(f),d.keepRuntimeAlive=()=>0t)}),t2=fs((n,e)=>{e.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(...e){var a=e.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,a+`\n`);return}console.error(a)}function threadAlert(...e){var a=e.join(" ");postMessage({cmd:"alert",text:a,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,a)=>{var r=Module.wasmModule;Module.wasmModule=null;var t=new WebAssembly.Instance(r,e);return a(t)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let r=[];self.onmessage=t=>r.push(t),self.startWorker=t=>{Module=t,postMessage({cmd:"loaded"});for(let s of r)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const t of e.data.handlers)Module[t]=(...s)=>{postMessage({cmd:"callHandler",handler:t,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var a=URL.createObjectURL(e.data.urlOrBlob);importScripts(a),URL.revokeObjectURL(a)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(r){if(r!="unwind")throw r}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(r){throw Module.__emscripten_thread_crashed?.(),r}}self.onmessage=handleMessage;\n'}),Fh,Gh,Cu,zo,Ms,$u,Wh,Vh,Hh,_0,yn,ao=Ce(()=>{Fh=K1(),Gh=e2(),zo=!1,Ms=!1,$u=!1,Wh=n=>{if(n===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+n+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Vh=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Hh=(n,e)=>n?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",_0=async n=>{if(zo)return Promise.resolve();if(Ms)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if($u)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ms=!0;let e=n.initTimeout,t=n.numThreads,r=n.simd,i=Wh(t),a=r&&Vh(),s=n.wasmPaths,o=typeof s=="string"?s:void 0,l=Hh(a,i),u=typeof s=="object"?s[l]:void 0,c=!1,h=[];if(e>0&&h.push(new Promise(p=>{setTimeout(()=>{c=!0,p()},e)})),h.push(new Promise((p,d)=>{let m=i?Gh:Fh,y={locateFile:(g,_)=>{if(i&&g.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([t2()],{type:"text/javascript"}));if(g.endsWith(".wasm")){if(u)return u;let w=o??_;return l==="ort-wasm-simd.wasm"?w+"ort-wasm-simd.jsep.wasm":l==="ort-wasm-simd-threaded.wasm"?w+"ort-wasm-simd-threaded.jsep.wasm":w+l}return _+g}};if(i)if(y.numThreads=t,typeof Blob>"u")y.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let g=`var ortWasmThreaded=${m.toString()};`;y.mainScriptUrlOrBlob=new Blob([g],{type:"text/javascript"})}m(y).then(g=>{Ms=!1,zo=!0,Cu=g,p()},g=>{Ms=!1,$u=!0,d(g)})})),await Promise.race(h),c)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},yn=()=>{if(zo&&Cu)return Cu;throw new Error("WebAssembly is not initialized yet.")}}),fn,Pl,an,wd=Ce(()=>{ao(),fn=(n,e)=>{let t=yn(),r=t.lengthBytesUTF8(n)+1,i=t._malloc(r);return t.stringToUTF8(n,i,r),e.push(i),i},Pl=(n,e,t,r)=>{if(typeof n=="object"&&n!==null){if(t.has(n))throw new Error("Circular reference in options");t.add(n)}Object.entries(n).forEach(([i,a])=>{let s=e?e+i:i;if(typeof a=="object")Pl(a,s+".",t,r);else if(typeof a=="string"||typeof a=="number")r(s,a.toString());else if(typeof a=="boolean")r(s,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},an=n=>{let e=yn(),t=e.stackSave();try{let r=e.stackAlloc(8);e._OrtGetLastError(r,r+4);let i=e.HEAP32[r/4],a=e.HEAPU32[r/4+1],s=a?e.UTF8ToString(a):"";throw new Error(`${n} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{e.stackRestore(t)}}}),y0,n2=Ce(()=>{ao(),wd(),y0=n=>{let e=yn(),t=0,r=[],i=n||{};try{if(n?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof n.logSeverityLevel!="number"||!Number.isInteger(n.logSeverityLevel)||n.logSeverityLevel<0||n.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${n.logSeverityLevel}`);if(n?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof n.logVerbosityLevel!="number"||!Number.isInteger(n.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${n.logVerbosityLevel}`);n?.terminate===void 0&&(i.terminate=!1);let a=0;return n?.tag!==void 0&&(a=fn(n.tag,r)),t=e._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),t===0&&an("Can't create run options."),n?.extra!==void 0&&Pl(n.extra,"",new WeakSet,(s,o)=>{let l=fn(s,r),u=fn(o,r);e._OrtAddRunConfigEntry(t,l,u)!==0&&an(`Can't set a run config entry: ${s} - ${o}.`)}),[t,r]}catch(a){throw t!==0&&e._OrtReleaseRunOptions(t),r.forEach(s=>e._free(s)),a}}}),qh,jh,Xh,Yh,v0,r2=Ce(()=>{ao(),wd(),qh=n=>{switch(n){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${n}`)}},jh=n=>{switch(n){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${n}`)}},Xh=n=>{n.extra||(n.extra={}),n.extra.session||(n.extra.session={});let e=n.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),n.executionProviders&&n.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(n.enableMemPattern=!1)},Yh=(n,e,t)=>{for(let r of e){let i=typeof r=="string"?r:r.name;switch(i){case"webnn":if(i="WEBNN",typeof r!="string"){let s=r;if(s?.deviceType){let o=fn("deviceType",t),l=fn(s.deviceType,t);yn()._OrtAddSessionConfigEntry(n,o,l)!==0&&an(`Can't set a session config entry: 'deviceType' - ${s.deviceType}.`)}if(s?.numThreads){let o=s.numThreads;(typeof o!="number"||!Number.isInteger(o)||o<0)&&(o=0);let l=fn("numThreads",t),u=fn(o.toString(),t);yn()._OrtAddSessionConfigEntry(n,l,u)!==0&&an(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s?.powerPreference){let o=fn("powerPreference",t),l=fn(s.powerPreference,t);yn()._OrtAddSessionConfigEntry(n,o,l)!==0&&an(`Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof r!="string"){let s=r;if(s?.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let o=fn("preferredLayout",t),l=fn(s.preferredLayout,t);yn()._OrtAddSessionConfigEntry(n,o,l)!==0&&an(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=fn(i,t);yn()._OrtAppendExecutionProvider(n,a)!==0&&an(`Can't append execution provider: ${i}.`)}},v0=n=>{let e=yn(),t=0,r=[],i=n||{};Xh(i);try{let a=qh(i.graphOptimizationLevel??"all"),s=jh(i.executionMode??"sequential"),o=typeof i.logId=="string"?fn(i.logId,r):0,l=i.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=i.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let c=typeof i.optimizedModelFilePath=="string"?fn(i.optimizedModelFilePath,r):0;if(t=e._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,s,!!i.enableProfiling,0,o,l,u,c),t===0&&an("Can't create session options."),i.executionProviders&&Yh(t,i.executionProviders,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let h=fn("enableGraphCapture",r),p=fn(i.enableGraphCapture.toString(),r);e._OrtAddSessionConfigEntry(t,h,p)!==0&&an(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[h,p]of Object.entries(i.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof p!="number"||!Number.isInteger(p)||p<0)throw new Error(`free dimension override value must be a non-negative integer: ${p}`);let d=fn(h,r);e._OrtAddFreeDimensionOverride(t,d,p)!==0&&an(`Can't set a free dimension override: ${h} - ${p}.`)}return i.extra!==void 0&&Pl(i.extra,"",new WeakSet,(h,p)=>{let d=fn(h,r),m=fn(p,r);e._OrtAddSessionConfigEntry(t,d,m)!==0&&an(`Can't set a session config entry: ${h} - ${p}.`)}),[t,r]}catch(a){throw t!==0&&e._OrtReleaseSessionOptions(t),r.forEach(s=>e._free(s)),a}}}),Uc,ta,Xs,bd,kl,xd,Bc,bt=Ce(()=>{Uc=n=>{switch(n){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${n}`)}},ta=n=>{switch(n){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${n}`)}},Xs=n=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][n],bd=n=>{switch(n){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${n}`)}},kl=n=>{switch(n){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${n}`)}},xd=n=>n==="float32"||n==="float16"||n==="int32"||n==="int64"||n==="uint32"||n==="uint8"||n==="bool",Bc=n=>{switch(n){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${n}`)}}}),Ol,w0=Ce(()=>{Ol=async n=>{if(typeof n=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(n))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let t=(void 0)(n),r=[];for await(let i of t)r.push(i);return new Uint8Array(Buffer.concat(r))}throw e}else{let e=await fetch(n);if(!e.ok)throw new Error(`failed to load external data file: ${n}`);let t=e.headers.get("Content-Length"),r=t?parseInt(t,10):0;if(r<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${n}, no response body.`);let i=e.body.getReader(),a;try{a=new ArrayBuffer(r)}catch(o){if(o instanceof RangeError){let l=Math.ceil(r/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw o}let s=0;for(;;){let{done:o,value:l}=await i.read();if(o)break;let u=l.byteLength;new Uint8Array(a,s,u).set(l),s+=u}return new Uint8Array(a,0,r)}}else return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n instanceof Uint8Array?n:new Uint8Array(n)}}),Kh,Zh,Qh,Jh,b0,ep,mn,wa=Ce(()=>{bt(),Kh=["V","I","W","E","F"],Zh=(n,e)=>{console.log(`[${Kh[n]},${new Date().toISOString()}]${e}`)},b0=(n,e)=>{Qh=n,Jh=e},ep=(n,e)=>{let t=kl(n),r=kl(Qh);t>=r&&Zh(t,typeof e=="function"?e():e)},mn=(...n)=>{Jh&&ep(...n)}}),x0,i2=Ce(()=>{bt(),x0=(n,e)=>new(bd(e))(n)}),Sd=Ce(()=>{}),Ru,No,Uo,tp,np,Iu,Fc,rp,S0,a2=Ce(()=>{wa(),Sd(),Ru=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),No=[],Uo=n=>Math.ceil(n/16)*16,tp=n=>{for(let e=0;enp++,Fc=async(n,e,t,r)=>{let i=Uo(t),a=n.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=n.getCommandEncoder();n.endComputePass(),s.copyBufferToBuffer(e,0,a,0,i),n.flush(),await a.mapAsync(GPUMapMode.READ);let o=a.getMappedRange();if(r){let l=r();return l.set(new Uint8Array(o,0,t)),l}else return new Uint8Array(o.slice(0,t))}finally{a.destroy()}},rp=class{constructor(n){this.backend=n,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[e]of Ru)No.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[])}upload(n,e){let t=e.buffer,r=e.byteOffset,i=e.byteLength,a=Uo(i),s=this.storageCache.get(n);if(!s)throw new Error("gpu data for uploading does not exist");if(s.originalSize!==i)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${i}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=o.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,r,i)),o.unmap();let u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o,0,s.gpuData.buffer,0,a),mn("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${n})`),this.buffersForUploadingPending.push(o)}memcpy(n,e){let t=this.storageCache.get(n);if(!t)throw new Error("source gpu data for memcpy does not exist");let r=this.storageCache.get(e);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=Uo(t.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(t.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(n,e,t){let r;if(t){if(r=this.externalBuffers.get(t),r===void 0)throw new Error("previous buffer is not registered");if(n===t)return mn("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${r}, buffer is the same, skip.`),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`);this.externalBuffers.delete(t)}else r=Iu();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:n},originalSize:e}),this.externalBuffers.set(n,r),mn("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${r}, registered.`),r}unregisterExternalBuffer(n){let e=this.externalBuffers.get(n);e!==void 0&&(this.storageCache.delete(e),this.externalBuffers.delete(n),mn("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(n,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=tp(n),r,i=(e&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(e&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let o=(i?this.freeBuffers:this.freeUniformBuffers).get(t);o?o.length>0?r=o.pop():r=this.backend.device.createBuffer({size:t,usage:e}):r=this.backend.device.createBuffer({size:t,usage:e})}else r=this.backend.device.createBuffer({size:t,usage:e});let s={id:Iu(),type:0,buffer:r};return this.storageCache.set(s.id,{gpuData:s,originalSize:n}),mn("verbose",()=>`[WebGPU] GpuDataManager.create(size=${n}) => id=${s.id}`),s}get(n){return this.storageCache.get(n)?.gpuData}release(n){let e=this.storageCache.get(n);if(!e)throw new Error("releasing data does not exist");return mn("verbose",()=>`[WebGPU] GpuDataManager.release(id=${n}), gpuDataId=${e.gpuData.id}`),this.storageCache.delete(n),this.buffersPending.push(e.gpuData.buffer),e.originalSize}async download(n,e){let t=this.storageCache.get(n);if(!t)throw new Error("data does not exist");await Fc(this.backend,t.gpuData.buffer,t.originalSize,e)}refreshPendingBuffers(){for(let n of this.buffersForUploadingPending)n.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let n of this.buffersPending){let e=Ru.get(n.size);if((n.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(n.size)||[];e===void 0||t.length>=e?n.destroy():t.push(n)}else if((n.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(n.size)||[];e===void 0||t.length>=e?n.destroy():t.push(n)}else n.destroy()}this.buffersPending=[]}else{let n=this.capturedPendingBuffers.get(this.backend.currentSessionId);n||(n=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,n));for(let e of this.buffersPending)n.push(e);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(n=>{n.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(n=>{n.forEach(e=>{e.destroy()})}),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(n=>{n.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(n){let e=this.capturedPendingBuffers.get(n);e&&(e.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(n))}},S0=(...n)=>new rp(...n)}),ip,sn,Mn=Ce(()=>{ip=class{constructor(n){Object.assign(this,n)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(n=>`${this[n]}`).join(";")),this.key}},sn=n=>new ip(n)}),ap,os,Ee,Dl,E0,Ed,Md,Dt=Ce(()=>{ap=class{static calcMatMulShape(n,e){return n[1]!==e[0]?void 0:[n[0],e[1]]}},os=class{static calcShape(n,e,t=!1){let r=n.length,i=e.length;if(r===0)return e;if(i===0)return n;let a=Math.max(n.length,e.length),s=new Array(a);if(t){if(r<2||i<2)return;let o=ap.calcMatMulShape([n[r-2],n[r-1]],[e[i-2],e[i-1]]);if(o===void 0)return;[s[a-2],s[a-1]]=o}for(let o=t?3:1;o<=a;o++){let l=r-o<0?1:n[r-o],u=i-o<0?1:e[i-o];if(l!==u&&l>1&&u>1)return;let c=Math.max(l,u);if(l&&u)s[a-o]=Math.max(l,u);else{if(c>1)return;s[a-o]=0}}return s}static isValidBroadcast(n,e){let t=n.length,r=e.length;if(t>r)return!1;for(let i=1;i<=t;i++)if(n[t-i]!==1&&n[t-i]!==e[r-i])return!1;return!0}},Ee=class bl{static size(e){return bl.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,t=4){let r=e.length;if(r===0)return[];let i=new Array(r),a=r-1;for(;a>=0;){if(e[a]%t===0){i[a]=e[a]/t;break}if(t%e[a]!==0)throw new Error("cannot convert shape");i[a]=1,t/=e[a],a--}for(a--;a>=0;a--)i[a]=e[a];return i}static sizeFromDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return bl.getSizeFromDimensionRange(e,t,e.length)}static sizeToDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${e.length} dimensions.`);return bl.getSizeFromDimensionRange(e,0,t)}static getSizeFromDimensionRange(e,t,r){let i=1;for(let a=t;a=0;--i)r[i]=r[i+1]*e[i+1];return r}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map(r=>this.normalizeAxis(r,t??e.length))}static sortBasedOnPerm(e,t){return t?t.map(r=>e[r]):e.slice().reverse()}static padShape(e,t){let r=e.length;return e.map((i,a)=>i+t[a]+t[a+r])}static areEqual(e,t){return e.length!==t.length?!1:e.every((r,i)=>r===t[i])}},Dl=class Ns{static adjustPoolAttributes(e,t,r,i,a,s){if(!e&&r.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let o=0;o=r.length?r.push(t[o+2]):r[o]=t[o+2];for(let o=0;o=r[o]||s[o+r.length]>=r[o])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,t,r,i,a,s,o){if(o){if(a.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{bt(),Dt(),ls=64,Bo=(n,e)=>{if(e===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(n){case 10:return e>1?`vec${e}`:"f16";case 1:return e>1?`vec${e}`:"f32";case 6:return e>1?`vec${e}`:"i32";case 12:return e>1?`vec${e}`:"u32";case 7:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(e!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${n}`)}},Rn=(n,e=1)=>{let t=Bo(n,e);return typeof t=="string"?t:t[0]},tr=(n,e=1)=>{let t=Bo(n,e);return typeof t=="string"?t:t[1]},gt=(...n)=>{let e=[];return n.forEach(t=>{t.length!==0&&e.push({type:12,data:t},{type:12,data:Ee.computeStrides(t)})}),e},vn=n=>n%4===0?4:n%2===0?2:1,ui=(n="f32",e,t="0")=>!e||e===1?`${n}(${t})`:`vec${e}<${n}>(${t})`,es=(n,e,t)=>n==="f32"?t:e===1?`f32(${t})`:`vec${e}(${t})`,zi=(n,e)=>e===4?`(${n}.x + ${n}.y + ${n}.z + ${n}.w)`:e===2?`(${n}.x + ${n}.y)`:e===3?`(${n}.x + ${n}.y + ${n}.z)`:n,Et=(n,e,t,r)=>n.startsWith("uniforms.")&&t>4?typeof e=="string"?r==="f16"?`${n}[(${e}) / 8][(${e}) % 8 / 4][(${e}) % 8 % 4]`:`${n}[(${e}) / 4][(${e}) % 4]`:r==="f16"?`${n}[${Math.floor(e/8)}][${Math.floor(e%8/4)}][${e%8%4}]`:`${n}[${Math.floor(e/4)}][${e%4}]`:t>1?`${n}[${e}]`:n,Fo=(n,e,t,r,i)=>{let a=typeof t=="number",s=a?t:t.length,o=[...new Array(s).keys()],l=s<2?"u32":s<=4?`vec${s}`:`array`,u=Bo(e,i),c=typeof u=="string"?u:u[1],h=typeof u=="string"?u:u[0],p={indices:l,value:c,storage:h,tensor:e},d=W=>typeof W=="string"?W:`${W}u`,m={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},y=a?"uniforms.":"",g=`${y}${n}_shape`,_=`${y}${n}_strides`,w="";for(let W=0;W ${p.indices} { var indices: ${p.indices}; var current = offset; ${w} return indices; }`,E=W=>(m.offsetToIndices=!0,s<2?W:`o2i_${n}(${W})`),T=[];if(s>=2)for(let W=s-1;W>=0;W--)T.push(`${Et(_,W,s)} * (indices[${W}])`);let I=s<2?"":` fn i2o_${n}(indices: ${p.indices}) -> u32 { return ${T.join("+")}; }`,C=W=>(m.indicesToOffset=!0,s<2?W:`i2o_${n}(${W})`),B=(...W)=>s===0?"0u":`${p.indices}(${W.map(d).join(",")})`,R=(W,ae)=>s<2?`${W}`:`${Et(W,ae,s)}`,k=(W,ae,Z)=>s<2?`${W}=${Z};`:`${Et(W,ae,s)}=${Z};`,j={},Q=(W,ae)=>{m.broadcastedIndicesToOffset=!0;let Z=`${ae.name}broadcastedIndicesTo${n}Offset`;if(Z in j)return`${Z}(${W})`;let de=[];for(let ye=s-1;ye>=0;ye--){let Pe=ae.indicesGet("outputIndices",ye+ae.rank-s);de.push(`${R(_,ye)} * (${Pe} % ${R(g,ye)})`)}return j[Z]=`fn ${Z}(outputIndices: ${ae.type.indices}) -> u32 { return ${de.length>0?de.join("+"):"0u"}; }`,`${Z}(${W})`},ie=(W,ae)=>(()=>{if(p.storage===p.value)return`${n}[${W}]=${ae};`;if(p.storage==="vec2"&&p.value==="i32")return`${n}[${W}]=vec2(u32(${ae}), select(0u, 0xFFFFFFFFu, ${ae} < 0));`;if(p.storage==="vec2"&&p.value==="u32")return`${n}[${W}]=vec2(u32(${ae}), 0u);`;if(p.storage==="u32"&&p.value==="vec4")return`${n}[${W}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ae}));`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),F=W=>(()=>{if(p.storage===p.value)return`${n}[${W}]`;if(p.storage==="vec2"&&p.value==="i32")return`i32(${n}[${W}].x)`;if(p.storage==="vec2"&&p.value==="u32")return`u32(${n}[${W}].x)`;if(p.storage==="u32"&&p.value==="vec4")return`vec4(bool(${n}[${W}] & 0xFFu), bool(${n}[${W}] & 0xFF00u), bool(${n}[${W}] & 0xFF0000u), bool(${n}[${W}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),$=s<2?"":` fn get_${n}ByIndices(indices: ${p.indices}) -> ${c} { return ${F(`i2o_${n}(indices)`)}; }`,L=s<2?"":(()=>{let W=o.map(Z=>`d${Z}: u32`).join(", "),ae=o.map(Z=>`d${Z}`).join(", ");return` fn get_${n}(${W}) -> ${c} { return get_${n}ByIndices(${B(ae)}); }`})(),H=(...W)=>{if(W.length!==s)throw new Error(`indices length must be ${s}`);let ae=W.map(d).join(",");return s===0?F("0u"):s===1?F(ae[0]):(m.get=!0,m.getByIndices=!0,m.indicesToOffset=!0,`get_${n}(${ae})`)},K=W=>s<2?F(W):(m.getByIndices=!0,m.indicesToOffset=!0,`get_${n}ByIndices(${W})`),X=s<2?"":` fn set_${n}ByIndices(indices: ${p.indices}, value: ${c}) { ${ie(`i2o_${n}(indices)`,"value")} }`,J=s<2?"":(()=>{let W=o.map(Z=>`d${Z}: u32`).join(", "),ae=o.map(Z=>`d${Z}`).join(", ");return` fn set_${n}(${W}, value: ${c}) { set_${n}ByIndices(${B(ae)}, value); }`})();return{impl:()=>{let W=[],ae=!1;return m.offsetToIndices&&(W.push(b),ae=!0),m.indicesToOffset&&(W.push(I),ae=!0),m.broadcastedIndicesToOffset&&(Object.values(j).forEach(Z=>W.push(Z)),ae=!0),m.set&&(W.push(J),ae=!0),m.setByIndices&&(W.push(X),ae=!0),m.get&&(W.push(L),ae=!0),m.getByIndices&&(W.push($),ae=!0),!a&&ae&&W.unshift(`const ${g} = ${p.indices}(${t.join(",")});`,`const ${_} = ${p.indices}(${Ee.computeStrides(t).join(",")});`),W.join(` `)},type:p,offsetToIndices:E,indicesToOffset:C,broadcastedIndicesToOffset:Q,indices:B,indicesGet:R,indicesSet:k,set:(...W)=>{if(W.length!==s+1)throw new Error(`indices length must be ${s}`);let ae=W[s];if(typeof ae!="string")throw new Error("value must be string");let Z=W.slice(0,s).map(d).join(",");return s===0?ie("0u",ae):s===1?ie(Z[0],ae):(m.set=!0,m.setByIndices=!0,m.indicesToOffset=!0,`set_${n}(${Z}, ${ae})`)},setByOffset:ie,setByIndices:(W,ae)=>s<2?ie(W,ae):(m.setByIndices=!0,m.indicesToOffset=!0,`set_${n}ByIndices(${W}, ${ae});`),get:H,getByOffset:F,getByIndices:K,usage:r,name:n,strides:_,shape:g,rank:s}},Te=(n,e,t,r=1)=>Fo(n,e,t,"input",r),ct=(n,e,t,r=1)=>Fo(n,e,t,"output",r),Td=(n,e,t,r=1)=>Fo(n,e,t,"internal",r),sp=class{constructor(n,e){this.normalizedDispatchGroup=n,this.limits=e,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(n){return`if (global_idx >= ${typeof n=="number"?`${n}u`:n}) { return; }`}mainStart(n=ls){let e=typeof n=="number"?n:n[0],t=typeof n=="number"?1:n[1],r=typeof n=="number"?1:n[2];if(e>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${e}, ${t}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(e*t*r>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${e}, ${t}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,s=i?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${e*t*r}u + local_idx;`;return`@compute @workgroup_size(${e}, ${t}, ${r}) fn main(${a}) { ${s} `}appendVariableUniforms(n){n.rank!==0&&(n.shape.startsWith("uniforms.")&&this.uniforms.push({name:n.shape.replace("uniforms.",""),type:"u32",length:n.rank}),n.strides.startsWith("uniforms.")&&this.uniforms.push({name:n.strides.replace("uniforms.",""),type:"u32",length:n.rank}))}declareVariable(n,e){if(n.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(n),this.appendVariableUniforms(n);let t=n.usage==="input"?"read":"read_write",r=n.type.storage;return`@group(0) @binding(${e}) var ${n.name}: array<${r}>;`}declareVariables(...n){return n.map(e=>this.declareVariable(e,this.variableIndex++)).join(` `)}registerInternalVariable(n){if(n.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(n),this.appendVariableUniforms(n)}registerInternalVariables(...n){return n.forEach(e=>this.registerInternalVariable(e)),this}registerUniform(n,e,t=1){return this.uniforms.push({name:n,type:e,length:t}),this}registerUniforms(n){return this.uniforms=this.uniforms.concat(n),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let n=[];for(let{name:e,type:t,length:r}of this.uniforms)if(r&&r>4)t==="f16"?n.push(`@align(16) ${e}:array, ${Math.ceil(r/8)}>`):n.push(`${e}:array, ${Math.ceil(r/4)}>`);else{let i=r==null||r===1?t:`vec${r}<${t}>`;n.push(`${e}:${i}`)}return` struct Uniforms { ${n.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(n=>n.impl()).join(` `)+this.internalVariables.map(n=>n.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let n=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map(e=>[n(e.type),e.length??1])}},M0=(n,e)=>new sp(n,e),Ys=(n,e)=>{let t=n.length,r=[];for(let i=0;i1&&s===1&&r.unshift(a)}return r}}),op,Pu,lp,up,pi,T0,A0,so=Ce(()=>{bt(),Dt(),Mn(),Ot(),op=n=>{if(!n||n.length!==1)throw new Error("Transpose requires 1 input.")},Pu=(n,e)=>e&&e.length!==n?[...new Array(n).keys()].reverse():e,lp=(n,e)=>Ee.sortBasedOnPerm(n,Pu(n.length,e)),up=(n,e,t,r)=>{let i=[];i.push(`fn perm(i: ${r.type.indices}) -> ${t.type.indices} { var a: ${t.type.indices};`);for(let a=0;a{let t=n.dataType,r=n.dims.length,i=Pu(r,e),a=lp(n.dims,i),s=ct("output",t,a.length),o=Te("a",t,r),l=u=>` ${u.registerUniform("output_size","u32").declareVariables(o,s)} ${up(i,r,o,s)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${s.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${s.setByOffset("global_idx",o.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:["rank"]},getRunData:u=>{let c=Ee.size(a);return{outputs:[{dims:a,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},...gt(u[0].dims,a)]}},getShaderSource:l}},T0=(n,e)=>{op(n.inputs),n.compute(pi(n.inputs[0],e.perm))},A0=n=>sn({perm:n.perm})}),cp,dp,hp,pp,fp,mp,gp,_p,yp,vp,Er,C0,$0,R0,I0,P0,k0,O0,D0,L0,z0,s2=Ce(()=>{bt(),Dt(),Ot(),Ad(),so(),cp={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},dp={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},hp={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},pp={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},fp=(n,e)=>{let t=[];for(let r=e-n;r{let t=[],r=n.length;for(let a=0;an[a]);return[t,i]},gp=(n,e)=>{let t=n.length+e.length,r=[],i=0;for(let a=0;a{for(let t=0;t{let t=[];if(!_p(n,e)){for(let r=0;rt.push(r))}return t},vp=(n,e,t,r,i,a,s)=>{let o=t[0].dims,l=Ee.size(a),u=Ee.size(s),c=Te("_A",t[0].dataType,o),h=ct("output",i,a),p=32,d=` var aBestValues : array; `;return{name:n,shaderCache:e,getShaderSource:m=>` ${m.registerUniform("reduceSize","u32").declareVariables(c,h)} ${d} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${m.mainStart(p)} let outputIndex = global_idx / ${p}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${hp[r]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${p}) { let candidate = f32(${c.getByOffset("offset + k")}); bestValue = ${cp[r]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${p}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${dp[r]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${h.setByOffset("outputIndex",`${r==="mean"?`${h.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${h.type.storage}(${pp[r]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},Er=(n,e,t,r)=>{let i=n.inputs.length===1?t:Gc(n.inputs,t),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=n.inputs[0].dims.map((d,m)=>m));let s=Ee.normalizeAxes(a,n.inputs[0].dims.length),o=s,l=n.inputs[0],u=yp(o,n.inputs[0].dims.length);u.length>0&&(l=n.compute(pi(n.inputs[0],u),{inputs:[0],outputs:[-1]})[0],o=fp(o.length,l.dims.length));let[c,h]=mp(l.dims,o),p=c;i.keepDims&&(p=gp(c,s)),n.compute(vp(e,{hint:i.cacheKey,inputDependencies:["type"]},[l],r,n.inputs[0].dataType,p,h),{inputs:[l]})},C0=(n,e)=>{Er(n,"ReduceMeanShared",e,"mean")},$0=(n,e)=>{Er(n,"ReduceL1Shared",e,"l1")},R0=(n,e)=>{Er(n,"ReduceL2Shared",e,"l2")},I0=(n,e)=>{Er(n,"ReduceLogSumExpShared",e,"logSumExp")},P0=(n,e)=>{Er(n,"ReduceMaxShared",e,"max")},k0=(n,e)=>{Er(n,"ReduceMinShared",e,"min")},O0=(n,e)=>{Er(n,"ReduceProdShared",e,"prod")},D0=(n,e)=>{Er(n,"ReduceSumShared",e,"sum")},L0=(n,e)=>{Er(n,"ReduceSumSquareShared",e,"sumSquare")},z0=(n,e)=>{Er(n,"ReduceLogSumShared",e,"logSum")}}),Mr,wp,Ll,Gc,Tr,bp,xp,Sp,Ep,Mp,Tp,Ap,Cp,$p,Rp,Ar,N0,U0,B0,F0,G0,W0,V0,H0,q0,j0,Ad=Ce(()=>{bt(),Dt(),Mn(),Ot(),s2(),Mr=n=>{if(!n||n.length===0||n.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(n.length===2&&n[1].dims.length!==1)throw new Error("Invalid axes input dims.")},wp=n=>["","",`var value = ${n.getByIndices("input_indices")};`,""],Ll=(n,e,t,r,i,a,s=!1,o=!1)=>{let l=[],u=t[0].dims,c=u.length,h=Ee.normalizeAxes(i,c),p=!o&&h.length===0;u.forEach((y,g)=>{p||h.indexOf(g)>=0?s&&l.push(1):l.push(y)});let d=l.length,m=Ee.size(l);return{name:n,shaderCache:e,getShaderSource:y=>{let g=[],_=Te("_A",t[0].dataType,c),w=ct("output",a,d),b=r(_,w,h),E=b[2];for(let T=0,I=0;T=0?(s&&I++,E=`for(var j${T}: u32 = 0; j${T} < ${u[T]}; j${T}++) { ${b[2].includes("last_index")?`let last_index = j${T};`:""} ${_.indicesSet("input_indices",T,`j${T}`)} ${E} }`):(g.push(`${_.indicesSet("input_indices",T,w.indicesGet("output_indices",I))};`),I++);return` ${y.registerUniform("output_size","u32").declareVariables(_,w)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${_.type.indices}; let output_indices = ${w.offsetToIndices("global_idx")}; ${g.join(` `)} ${b[0]} // init ops for reduce max/min ${b[1]} ${E} ${b[3]} ${b.length===4?w.setByOffset("global_idx","value"):b.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...gt(u,l)]})}},Gc=(n,e)=>{let t=[];return n[1].dims[0]>0&&n[1].getBigInt64Array().forEach(r=>t.push(Number(r))),sn({axes:t,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},Tr=(n,e,t,r)=>{let i=n.inputs,a=i.length===1?t:Gc(i,t);n.compute(Ll(e,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?wp:r,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},bp=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceLogSum",e,(t,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},xp=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceL1",e,(t,r)=>[`var value = ${r.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Sp=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceL2",e,(t,r)=>[`var t = ${r.type.value}(0); var value = ${r.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ep=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceLogSumExp",e,(t,r)=>[`var value = ${r.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Mp=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceMax",e,(t,r,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(t.indicesSet("input_indices",s,0));return[`${a.join(` `)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Tp=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceMean",e,(t,r,i)=>{let a=1;for(let s=0;s=0||i.length===0)&&(a*=n.inputs[0].dims[s]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${r.type.value}(sum / ${a});`]})},Ap=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceMin",e,(t,r,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(`input_indices[${s}] = 0;`);return[`${a.join(` `)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Cp=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceProd",e,(t,r)=>[`var value = ${r.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},$p=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceSum",e,(t,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Rp=(n,e)=>{Mr(n.inputs),Tr(n,"ReduceSumSquare",e,(t,r)=>[`var t = ${r.type.value}(0); var value = ${r.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},Ar=(n,e,t)=>{if(e.length===0)return t;let r=1,i=1;for(let a=0;a1024},N0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Tp(n,e):C0(n,e)},U0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?xp(n,e):$0(n,e)},B0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Sp(n,e):R0(n,e)},F0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ep(n,e):I0(n,e)},G0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Mp(n,e):P0(n,e)},W0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ap(n,e):k0(n,e)},V0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Cp(n,e):O0(n,e)},H0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?$p(n,e):D0(n,e)},q0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Rp(n,e):L0(n,e)},j0=(n,e)=>{Ar(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?bp(n,e):z0(n,e)}}),ku,X0,Y0,Wc,o2=Ce(()=>{bt(),Mn(),Ad(),ku=n=>{if(!n||n.length===0||n.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(n[0].dataType!==1)throw new Error("Invalid input type.")},X0=(n,e)=>{ku(n.inputs);let t=(r,i,a)=>{let s=[];for(let o=0;o=0||a.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` `)}`,`var value = ${r.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${r.getByIndices("input_indices")} ${e.selectLastIndex>0?"<=":"<"} value) { value = ${r.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};n.compute(Ll("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],t,[e.axis],7,e.keepDims),{inputs:[0]})},Y0=(n,e)=>{ku(n.inputs);let t=(r,i,a)=>{let s=[];for(let o=0;o=0||a.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` `)}`,`var value = ${r.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${r.getByIndices("input_indices")} ${e.selectLastIndex>0?">=":">"} value) { value = ${r.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};n.compute(Ll("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],t,[e.axis],7,e.keepDims),{inputs:[0]})},Wc=n=>sn(n)}),Ip,Pp,kp,zl,K0,Z0,Q0=Ce(()=>{bt(),Dt(),Mn(),Ot(),Ip=(n,e)=>{if(!n||n.length<1)throw new Error("too few inputs");let t=0,r=n[t],i=r.dataType,a=r.dims.length;n.forEach((s,o)=>{if(o!==t){if(s.dataType!==i)throw new Error("input tensors should be one type");if(s.dims.length!==a)throw new Error("input tensors should have the same shape");s.dims.forEach((l,u)=>{if(u!==e&&l!==r.dims[u])throw new Error("non concat dimensions must match")})}})},Pp=(n,e)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${e}); for (var i: u32 = 0u; i < ${n}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${n}u; }`,kp=(n,e)=>{let t=n.length,r=[];for(let i=0;i{let i=Ee.size(t),a=new Array(n.length),s=new Array(n.length),o=0,l=[],u=[],c=[{type:12,data:i}];for(let y=0;y`uniforms.sizeInConcatAxis${y}`).join(","),m=y=>` ${(()=>{y.registerUniform("outputSize","u32");for(let g=0;g(${d}); ${p} -= sizeInConcatAxis[inputIndex - 1u]; } ${kp(s,h)} }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:r}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c}),getShaderSource:m}},K0=(n,e)=>{let t=n.inputs,r=t[0].dims,i=Ee.normalizeAxis(e.axis,r.length);Ip(t,i);let a=r.slice();a[i]=t.reduce((o,l)=>o+(l.dims.length>i?l.dims[i]:0),0);let s=t.filter(o=>Ee.size(o.dims)>0);n.compute(zl(s,i,a,t[0].dataType),{inputs:s})},Z0=n=>sn({axis:n.axis})}),Op,Dp,Lp,zp,Nl,Np,J0,ey=Ce(()=>{bt(),Sd(),Ot(),Q0(),Op=(n,e)=>{let t=n[0],r=n[1],i=n[2],a=n[3],s=n[4],o=n[5];if(s&&o)throw new Error("Attention cannot have both past and relative_position_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],u=t.dims[1],c=t.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(r.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(r.dims[0]!==c)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let h=i.dims[0]/3,p=h,d=p;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let b of e.qkvHiddenSizes)if(b%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");h=e.qkvHiddenSizes[0],p=e.qkvHiddenSizes[1],d=e.qkvHiddenSizes[2]}let m=u;if(h!==p)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==h+p+d)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let y=0;if(s){if(p!==d)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(s.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(s.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==e.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==p/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(y=s.dims[3])}let g=m+y,_=-1,w=0;if(a)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");return{batchSize:l,sequenceLength:u,pastSequenceLength:y,kvSequenceLength:m,totalSequenceLength:g,maxSequenceLength:_,inputHiddenSize:c,hiddenSize:h,vHiddenSize:d,headSize:Math.floor(h/e.numHeads),vHeadSize:Math.floor(d/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:w,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Dp=(n,e,t,r)=>{let i=vn(r),a=64,s=r/i;s{let d=ct("x",e.dataType,e.dims,i),m=[{name:"d_inv",type:tr(e.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${p.registerUniforms(m).declareVariables(d)} ${p.mainStart([a,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = workgroup_id.x * uniforms.d_comp + local_offset; var thread_max_vector = ${c}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${c}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(i){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${i}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${a}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${c}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${c}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(i){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${i}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${a}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${d.type.value}(uniforms.d_inv); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${c}(x[offset + i]); x[offset + i] = ${d.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${a};${u};${i}`},getShaderSource:h,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:l})}},Lp=(n,e,t,r,i,a,s)=>{let o=s+i.kvSequenceLength,l=[i.batchSize,i.numHeads,i.sequenceLength,o],u=a.scale===0?1/Math.sqrt(i.headSize):a.scale,c=vn(i.headSize),h=i.headSize/c,p=12,d={x:Math.ceil(o/p),y:Math.ceil(i.sequenceLength/p),z:i.batchSize*i.numHeads},m=[{type:12,data:i.sequenceLength},{type:12,data:h},{type:12,data:o},{type:12,data:i.numHeads},{type:1,data:u}],y=r?["type","type","type"]:["type","type"],g=_=>{let w=Te("q",e.dataType,e.dims,c),b=Te("key",t.dataType,t.dims,c),E=[w,b];r&&E.push(Te("relative_position_bias",r.dataType,r.dims));let T=ct("output",e.dataType,l),I=tr(1,c),C=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return` const TILE_SIZE = ${p}u; var tileQ: array<${w.type.storage}, ${p*p}>; var tileK: array<${w.type.storage}, ${p*p}>; ${_.registerUniforms(C).declareVariables(...E,T)} ${_.mainStart([p,p,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K; var value = ${I}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x]; } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${I}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(c){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${c}`)}})()}; output[outputIdx] = ${T.type.value} (sum * uniforms.alpha) + ${r?"relative_position_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${c}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e.dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:m}),getShaderSource:g}},zp=(n,e,t,r,i)=>{let a=i+r.kvSequenceLength,s=[r.batchSize,r.sequenceLength,r.vHiddenSize],o=12,l={x:Math.ceil(r.vHeadSize/o),y:Math.ceil(r.sequenceLength/o),z:r.batchSize*r.numHeads},u=[{type:12,data:r.sequenceLength},{type:12,data:a},{type:12,data:r.vHeadSize},{type:12,data:r.numHeads},{type:12,data:r.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:s,dataType:e.dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:u}),getShaderSource:c=>{let h=Te("probs",e.dataType,e.dims),p=Te("v",t.dataType,t.dims),d=ct("output",e.dataType,s),m=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return` const TILE_SIZE = ${o}u; var tileQ: array<${h.type.value}, ${o*o}>; var tileK: array<${h.type.value}, ${o*o}>; ${c.registerUniforms(m).declareVariables(h,p,d)} ${c.mainStart([o,o,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; let offsetB = headIdx * (uniforms.N * uniforms.K) + n; var value = ${h.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N]; } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`}}},Nl=(n,e,t,r,i,a,s,o,l,u,c)=>{let h=n.outputCount>1,p=n.outputCount>2,d=h&&p?u.pastSequenceLength:0,m=d+u.kvSequenceLength,y=[u.batchSize,u.numHeads,m,u.headSize],g=s?[s,t]:[t],_=h?n.compute(zl(g,2,y,t.dataType),{inputs:g,outputs:[1]})[0]:t,w=[u.batchSize,u.numHeads,m,u.headSize],b=o?[o,r]:[r],E=p?n.compute(zl(b,2,w,r.dataType),{inputs:b,outputs:[2]})[0]:r,T=[e,_];l&&T.push(l);let I=n.compute(Lp(n,e,_,l,u,c,d),{inputs:T,outputs:[-1]})[0];n.compute(Dp(n,I,u.batchSize*u.numHeads*u.sequenceLength,m),{inputs:[I],outputs:[]});let C=[I,E];n.compute(zp(n,I,E,u,d),{inputs:C,outputs:[0]})},Np=(n,e)=>{let t=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],r=e.sequenceLength,i=e.inputHiddenSize,a=e.headSize,s=12,o={x:Math.ceil(e.headSize/s),y:Math.ceil(e.sequenceLength/s),z:e.batchSize*e.numHeads},l=[n.inputs[0],n.inputs[1],n.inputs[2]],u=[{type:12,data:r},{type:12,data:i},{type:12,data:a},{type:12,data:e.numHeads},{type:12,data:e.headSize},{type:12,data:e.hiddenSize},{type:12,data:e.hiddenSize+e.hiddenSize+e.vHiddenSize}],c=h=>{let p=ct("output_q",l[0].dataType,t),d=ct("output_k",l[0].dataType,t),m=ct("output_v",l[0].dataType,t),y=Te("input",l[0].dataType,l[0].dims),g=Te("weight",l[1].dataType,l[1].dims),_=Te("bias",l[2].dataType,l[2].dims),w=y.type.storage,b=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${s}u; var tileInput: array<${w}, ${s*s}>; var tileWeightQ: array<${w}, ${s*s}>; var tileWeightK: array<${w}, ${s*s}>; var tileWeightV: array<${w}, ${s*s}>; ${h.registerUniforms(b).declareVariables(y,g,_,p,d,m)} ${h.mainStart([s,s,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${w}(0); var valueK = ${w}(0); var valueV = ${w}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:n.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:u}),getShaderSource:c},{inputs:l,outputs:[-1,-1,-1]})},J0=(n,e)=>{let t=Op(n.inputs,e),[r,i,a]=Np(n,t);return Nl(n,r,i,a,n.inputs[4],void 0,void 0,void 0,n.inputs[5],t,e)}}),Up,Bp,Fp,ty,l2=Ce(()=>{Ur(),bt(),Dt(),Mn(),Ot(),Up=(n,e)=>{if(!n||n.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(r,i,a)=>{let s=i.length;if(s!==r.length)throw new Error(`${a}: num dimensions != ${s}`);i.forEach((o,l)=>{if(o!==r[l])throw new Error(`${a}: dim[${l}] do not match`)})};if(n[0].dims.length>1){let r=e.format==="NHWC"?e.spatial?n[0].dims.slice(-1):n[0].dims.slice(-1).concat(n[0].dims.slice(1,n[0].dims.length-1)):n[0].dims.slice(1,e.spatial?2:void 0);t(n[1].dims,r,"Invalid input scale"),t(n[2].dims,r,"Invalid input B"),t(n[3].dims,r,"Invalid input mean"),t(n[4].dims,r,"Invalid input var")}else t(n[1].dims,[1],"Invalid input scale"),t(n[2].dims,[1],"Invalid input B"),t(n[3].dims,[1],"Invalid input mean"),t(n[4].dims,[1],"Invalid input var")},Bp=(n,e)=>{let{epsilon:t,spatial:r,format:i}=e,a=n[0].dims,s=r?vn(a[a.length-1]):1,o=i==="NHWC"&&a.length>1?s:1,l=Ee.size(a)/s,u=r,c=u?a.length:a,h=Te("x",n[0].dataType,n[0].dims,s),p=Te("scale",n[1].dataType,n[1].dims,o),d=Te("bias",n[2].dataType,n[2].dims,o),m=Te("inputMean",n[3].dataType,n[3].dims,o),y=Te("inputVar",n[4].dataType,n[4].dims,o),g=ct("y",n[0].dataType,c,s),_=()=>{let b="";if(r)b=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${s}`:"outputIndices[1]"};`;else if(i==="NCHW")b=` ${g.indicesSet("outputIndices","0","0")} let cOffset = ${g.indicesToOffset("outputIndices")};`;else{b=`var cIndices = ${p.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let E=1;E` const epsilon = ${t}; ${b.registerUniform("outputSize","u32").declareVariables(h,p,d,m,y,g)} ${b.mainStart()} ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${g.offsetToIndices(`global_idx * ${s}`)}; ${_()} let scale = ${p.getByOffset("cOffset")}; let bias = ${d.getByOffset("cOffset")}; let inputMean = ${m.getByOffset("cOffset")}; let inputVar = ${y.getByOffset("cOffset")}; let x = ${h.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${g.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${e.epsilon}_${e.format}_${r}_${s}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:w,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...gt(a)]:[{type:12,data:l}]})}},Fp=n=>sn(n),ty=(n,e)=>{let{inputs:t,outputCount:r}=n,i=Fp({...e,outputCount:r});if(Kt.webgpu.validateInputContent&&Up(t,i),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");n.compute(Bp(t,i))}}),Gp,Wp,ny,u2=Ce(()=>{Dt(),Ot(),Gp=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(n[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Wp=n=>{let e=n[0].dims,t=n[0].dims[2],r=Ee.size(e)/4,i=n[0].dataType,a=Te("input",i,e,4),s=Te("bias",i,[t],4),o=Te("residual",i,e,4),l=ct("output",i,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:u=>` const channels = ${t}u / 4; ${u.declareVariables(a,s,o,l)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(r)} let value = ${a.getByOffset("global_idx")} + ${s.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} }`}},ny=n=>{Gp(n.inputs),n.compute(Wp(n.inputs))}}),Vp,Gt,ry,iy,ay,sy,oy,ly,uy,cy,dy,Hp,hy,py,fy,my,xl,gy,Sl,_y,yy,vy,wy,by,xy,Sy,Ey,My,Ty,Ay,Cy,$y,Ry,Iy,Py,Ou,ky,Vc,Hc,Oy,Dy,Ly,Cd=Ce(()=>{bt(),Dt(),Mn(),Ot(),Vp=(n,e,t,r,i,a)=>{let s=Math.ceil(e/4),o="";typeof i=="string"?o=`${i}(a)`:o=i("a");let l=Te("inputData",t,[s],4),u=ct("outputData",r,[s],4);return` ${n.registerUniform("vec_size","u32").declareVariables(l,u)} ${a??""} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${l.getByOffset("global_idx")}; ${u.setByOffset("global_idx",o)} }`},Gt=(n,e,t,r,i,a=n.dataType)=>({name:e,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:s=>Vp(s,Ee.size(n.dims),n.dataType,a,t,r),getRunData:s=>({outputs:[{dims:n.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Ee.size(s[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(Ee.size(n.dims)/4)}]})}),ry=n=>{n.compute(Gt(n.inputs[0],"Abs","abs"))},iy=n=>{n.compute(Gt(n.inputs[0],"Acos","acos"))},ay=n=>{n.compute(Gt(n.inputs[0],"Acosh","acosh"))},sy=n=>{n.compute(Gt(n.inputs[0],"Asin","asin"))},oy=n=>{n.compute(Gt(n.inputs[0],"Asinh","asinh"))},ly=n=>{n.compute(Gt(n.inputs[0],"Atan","atan"))},uy=n=>{n.compute(Gt(n.inputs[0],"Atanh","atanh"))},cy=n=>sn(n),dy=(n,e)=>{let t;switch(e.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${e.to}`)}n.compute(Gt(n.inputs[0],"Cast",t,void 0,e.cacheKey,e.to))},Hp=n=>{let e=n.length>=2&&n[1].data!==0?n[1].getFloat32Array()[0]:Ed,t=n.length>=3&&n[2].data!==0?n[2].getFloat32Array()[0]:Md;return sn({min:e,max:t})},hy=(n,e)=>{let t=n.inputs.length===1?e:Hp(n.inputs),r=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"Clip",i=>`clamp(${i}, clip_min_, clip_max_)`,` const clip_min_: vec4<${r}> = vec4(${r}(${t.min})); const clip_max_: vec4<${r}> = vec4(${r}(${t.max})); `,t.cacheKey),{inputs:[0]})},py=n=>{n.compute(Gt(n.inputs[0],"Ceil","ceil"))},fy=n=>{n.compute(Gt(n.inputs[0],"Cos","cos"))},my=n=>{n.compute(Gt(n.inputs[0],"Cosh","cosh"))},xl=n=>sn(n),gy=(n,e)=>{let t=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"Elu",r=>`elu_vf32(${r})`,` const elu_alpha_ = ${t}(${e.alpha}); fn elu_f32(a: ${t}) -> ${t} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,e.cacheKey))},Sl=(n="f32")=>` const r0: ${n} = 0.3275911; const r1: ${n} = 0.254829592; const r2: ${n} = -0.284496736; const r3: ${n} = 1.421413741; const r4: ${n} = -1.453152027; const r5: ${n} = 1.061405429; fn erf_vf32(v: vec4<${n}>) -> vec4<${n}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,_y=n=>{let e=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"Erf",t=>`erf_vf32(${t})`,Sl(e)))},yy=n=>{n.compute(Gt(n.inputs[0],"Exp","exp"))},vy=n=>{n.compute(Gt(n.inputs[0],"Floor","floor"))},wy=n=>{let e=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,Sl(e)))},by=(n,e)=>{let t=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"LeakyRelu",r=>`select(leaky_relu_alpha_ * ${r}, ${r}, ${r} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${e.alpha});`,e.cacheKey))},xy=n=>{n.compute(Gt(n.inputs[0],"Not",e=>`!${e}`))},Sy=n=>{n.compute(Gt(n.inputs[0],"Neg",e=>`-${e}`))},Ey=n=>{n.compute(Gt(n.inputs[0],"Reciprocal",e=>`1.0/${e}`))},My=n=>{let e=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"Relu",t=>`select(vec4<${e}>(0.0), ${t}, ${t} > vec4<${e}>(0.0))`))},Ty=n=>{n.compute(Gt(n.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},Ay=n=>sn(n),Cy=(n,e)=>{let t=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"HardSigmoid",r=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${e.alpha} * ${r} + vec4<${t}>(${e.beta})))`,void 0,e.cacheKey))},$y=n=>{n.compute(Gt(n.inputs[0],"Sin","sin"))},Ry=n=>{n.compute(Gt(n.inputs[0],"Sinh","sinh"))},Iy=n=>{n.compute(Gt(n.inputs[0],"Sqrt","sqrt"))},Py=n=>{n.compute(Gt(n.inputs[0],"Tan","tan"))},Ou=n=>`sign(${n}) * (1 - exp(-2 * abs(${n}))) / (1 + exp(-2 * abs(${n})))`,ky=n=>{n.compute(Gt(n.inputs[0],"Tanh",Ou))},Vc=(n="f32")=>` const fast_gelu_a: ${n} = 0.5; const fast_gelu_b: ${n} = 0.7978845608028654; const fast_gelu_c: ${n} = 0.035677408136300125; fn tanh_v(v: vec4<${n}>) -> vec4<${n}> { return ${Ou("v")}; } `,Hc=n=>`(fast_gelu_a + fast_gelu_a * tanh_v(${n} * (fast_gelu_c * ${n} * ${n} + fast_gelu_b))) * ${n}`,Oy=n=>{let e=tr(n.inputs[0].dataType);n.compute(Gt(n.inputs[0],"FastGelu",Hc,Vc(e),void 0,n.inputs[0].dataType))},Dy=(n,e)=>{let t=tr(n.inputs[0].dataType);return n.compute(Gt(n.inputs[0],"ThresholdedRelu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${e.alpha});`,e.cacheKey)),0},Ly=n=>{n.compute(Gt(n.inputs[0],"Log","log"))}}),qp,jp,zy,c2=Ce(()=>{Dt(),Ot(),Cd(),qp=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(n[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},jp=n=>{let e=n[0].dims.slice();e[2]=e[2]/2;let t=Te("input",n[0].dataType,n[0].dims,4),r=Te("bias",n[0].dataType,[n[0].dims[2]],4),i=ct("output",n[0].dataType,e,4),a=Ee.size(e)/4,s=Rn(n[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:e,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:o=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${n[0].dims[2]/4/2}u; ${o.declareVariables(t,r,i)} ${Sl(s)} ${o.mainStart()} ${o.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${i.setByOffset("global_idx","valueLeft * geluRight")} }`}},zy=n=>{qp(n.inputs),n.compute(jp(n.inputs))}}),Xp,Yp,Cr,Ny,Uy,By,Fy,Gy,Wy,Vy,Hy,qy,jy,d2=Ce(()=>{bt(),Dt(),Ot(),Xp=(n,e,t,r,i,a,s,o,l,u,c,h)=>{let p,d;typeof o=="string"?p=d=(w,b)=>`${o}((${w}),(${b}))`:typeof o=="function"?p=d=o:(p=o.scalar,d=o.vector);let m=ct("outputData",c,r.length,4),y=Te("aData",l,e.length,4),g=Te("bData",u,t.length,4),_;if(i)if(a){let w=Ee.size(e)===1,b=Ee.size(t)===1,E=e.length>0&&e[e.length-1]%4===0,T=t.length>0&&t[t.length-1]%4===0;w||b?_=m.setByOffset("global_idx",d(w?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"),b?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"))):_=` let outputIndices = ${m.offsetToIndices("global_idx * 4u")}; let offsetA = ${y.broadcastedIndicesToOffset("outputIndices",m)}; let offsetB = ${g.broadcastedIndicesToOffset("outputIndices",m)}; ${m.setByOffset("global_idx",d(s||E?y.getByOffset("offsetA / 4u"):`${y.type.value}(${y.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||T?g.getByOffset("offsetB / 4u"):`${g.type.value}(${g.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else _=m.setByOffset("global_idx",d(y.getByOffset("global_idx"),g.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let w=(b,E,T="")=>{let I=`aData[indexA${E}][componentA${E}]`,C=`bData[indexB${E}][componentB${E}]`;return` let outputIndices${E} = ${m.offsetToIndices(`global_idx * 4u + ${E}u`)}; let offsetA${E} = ${y.broadcastedIndicesToOffset(`outputIndices${E}`,m)}; let offsetB${E} = ${g.broadcastedIndicesToOffset(`outputIndices${E}`,m)}; let indexA${E} = offsetA${E} / 4u; let indexB${E} = offsetB${E} / 4u; let componentA${E} = offsetA${E} % 4u; let componentB${E} = offsetB${E} % 4u; ${b}[${E}] = ${T}(${p(I,C)}); `};c===9?_=` var data = vec4(0); ${w("data",0,"u32")} ${w("data",1,"u32")} ${w("data",2,"u32")} ${w("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:_=` ${w("outputData[global_idx]",0)} ${w("outputData[global_idx]",1)} ${w("outputData[global_idx]",2)} ${w("outputData[global_idx]",3)} `}return` ${n.registerUniform("vec_size","u32").declareVariables(y,g,m)} ${h??""} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${_} }`},Yp=(n,e,t,r,i,a,s=t.dataType)=>{let o=!Ee.areEqual(t.dims,r.dims),l=t.dims,u=Ee.size(t.dims),c=!1,h=!1,p=[o];if(o){let d=os.calcShape(t.dims,r.dims,!1);if(!d)throw new Error("Can't perform binary op on the given tensors");l=d,u=Ee.size(l);let m=Ee.size(t.dims)===1,y=Ee.size(r.dims)===1,g=t.dims.length>0&&t.dims[t.dims.length-1]%4===0,_=r.dims.length>0&&r.dims[r.dims.length-1]%4===0;p.push(m),p.push(y),p.push(g),p.push(_);let w=1;for(let b=1;bd.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:d=>Xp(d,t.dims,r.dims,l,c,o,h,i,t.dataType,r.dataType,s,a),getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(Ee.size(l)/4)},...gt(t.dims,r.dims,l)]})}},Cr=(n,e,t,r,i,a)=>{n.compute(Yp(e,i??"",n.inputs[0],n.inputs[1],t,r,a))},Ny=n=>{Cr(n,"Add",(e,t)=>`${e}+${t}`)},Uy=n=>{Cr(n,"Div",(e,t)=>`${e}/${t}`)},By=n=>{Cr(n,"Equal",{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4(${e}==${t})`},void 0,void 0,9)},Fy=n=>{Cr(n,"Mul",(e,t)=>`${e}*${t}`)},Gy=n=>{let e=Te("input",n.inputs[0].dataType,n.inputs[0].dims).type.value;Cr(n,"Pow",{scalar:(t,r)=>`pow_custom(${t},${r})`,vector:(t,r)=>`pow_vector_custom(${t},${r})`},` fn pow_custom(a : ${e}, b : ${e}) -> ${e} { if (b == ${e}(0.0)) { return ${e}(1.0); } else if (a < ${e}(0.0) && f32(b) != floor(f32(b))) { return ${e}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${e}(1.0), round(f32(abs(b) % ${e}(2.0))) != 1.0) * ${e}(${e==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${e}>, b : vec4<${e}>) -> vec4<${e}> { // TODO: implement vectorized pow return vec4<${e}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},Wy=n=>{Cr(n,"Sub",(e,t)=>`${e}-${t}`)},Vy=n=>{Cr(n,"Greater",{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4(${e}>${t})`},void 0,void 0,9)},Hy=n=>{Cr(n,"Less",{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4(${e}<${t})`},void 0,void 0,9)},qy=n=>{Cr(n,"GreaterOrEqual",{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4(${e}>=${t})`},void 0,void 0,9)},jy=n=>{Cr(n,"LessOrEqual",{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4(${e}<=${t})`},void 0,void 0,9)}}),fa,ma,ga,$d,ba=Ce(()=>{bt(),Dt(),fa=(n,e,t="f32")=>{switch(n.activation){case"Relu":return`value = max(value, ${e}(0.0));`;case"Sigmoid":return`value = (${e}(1.0) / (${e}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${e}(${t}(uniforms.clip_min)), ${e}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${e}(0.0), min(${e}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${e}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${n.activation}`)}},ma=(n,e)=>{n.activation==="Clip"?e.push({type:1,data:n.clipMax},{type:1,data:n.clipMin}):n.activation==="HardSigmoid"?e.push({type:1,data:n.alpha},{type:1,data:n.beta}):n.activation==="LeakyRelu"&&e.push({type:1,data:n.alpha})},ga=(n,e)=>{n.activation==="Clip"?e.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):n.activation==="HardSigmoid"?e.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):n.activation==="LeakyRelu"&&e.push({name:"alpha",type:"f32"})},$d=n=>{let e=n?.activation||"";if(e==="HardSigmoid"){let[t,r]=n?.activation_params||[.2,.5];return{activation:e,alpha:t,beta:r}}else if(e==="Clip"){let[t,r]=n?.activation_params||[Ed,Md];return{activation:e,clipMax:r,clipMin:t}}else if(e==="LeakyRelu"){let[t]=n?.activation_params||[.01];return{activation:e,alpha:t}}return{activation:e}}}),Hn,Rd,Id=Ce(()=>{Hn=(n,e)=>{switch(n){case 1:return e;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${n}-component is not supported.`)}},Rd=n=>` ${n?"value = value + getBiasByOutputCoords(coords);":""} `}),Pd,Xy=Ce(()=>{Pd=n=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${n}.x), i32(${n}.y), i32(${n}.z), 1)); } `}),Kp,Zp,Ul,Du,Qp,Bl,Jp,kd,eu=Ce(()=>{bt(),Dt(),Ot(),ba(),Id(),Kp=(n,e)=>n?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${e?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${e?", batchIndices":""}); `,Zp=(n,e)=>n?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${e===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${e===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${e===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,Ul=(n,e,t="f32",r,i=!1,a=32,s=!1,o=32)=>{let l=e[1]*n[1],u=e[0]*n[0],c=i?l:a,h=i?a:l,p=c/e[0],d=a/e[1];if(!((i&&p===4&&n[1]===4||!i&&(p===3||p===4))&&c%e[0]===0&&a%e[1]===0&&n[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${p} and workPerThread[1] ${n[1]} must be 4. Otherwise, innerElementSize ${p} must be 3 or 4. tileAWidth ${c} must be divisible by workgroupSize[0]${e[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${n[0]} must be 4.`);return` var mm_Asub: array, ${c/p}>, ${h}>; var mm_Bsub: array, ${u/n[0]}>, ${a}>; const rowPerThread = ${n[1]}; const colPerThread = ${n[0]}; const innerElementSize = ${p}; const tileInner = ${a}; @compute @workgroup_size(${e[0]}, ${e[1]}, ${e[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${s?"0":"i32(globalId.z)"}; ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${l}; let num_tiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${o}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${d}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${Kp(i,r)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${d}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${r?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${p===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Zp(i,p)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Du=(n,e)=>n?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${e?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${e?", batchIndices":""}); `,Qp=n=>n?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Bl=(n,e,t="f32",r,i=!1,a=32,s=!1,o=32,l=!1)=>{let u=n[1]*e[1],c=n[0]*e[0],h=i?u:a,p=i?a:u;if(!(p%e[1]===0&&h%e[0]===0&&a%e[1]===0))throw new Error(`tileAHight ${p} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${h} must be divisible by workgroupSize[0]${e[0]}, tileInner ${a} must be divisible by workgroupSize[1]${e[1]}`);let d=p/e[1],m=h/e[0],y=a/e[1],g=l?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${u}; let globalColStart = i32(workgroupId.x) * ${c}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${e[1]}) { for (var inputCol = localCol; inputCol < ${h}; inputCol = inputCol + ${e[0]}) { ${Du(i,r)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${e[1]}) { for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${e[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${r?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${t}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${e[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${e[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${u}; let tileRowA = i32(localId.y) * ${d}; let tileColA = i32(localId.x) * ${m}; let tileRowB = i32(localId.y) * ${y}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${d}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${m}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Du(i,r)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${y}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${r?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${t}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Qp(i)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${p}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${n[1]}; const colPerThread = ${n[0]}; const tileInner = ${a}; @compute @workgroup_size(${e[0]}, ${e[1]}, ${e[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${s?"0":"i32(globalId.z)"}; ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${o}`:"0"}; var acc : array, rowPerThread>; // Without this initialization strange values show up in acc. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = 0.0; } } ${g} } `},Jp=(n,e,t,r,i,a=!1)=>{let[s,o,l]=i,[u,c,h,p]=r,d=Ys(s,l),m=Ys(o,l),y=Rn(r[0].type.tensor),g=()=>{let w=c.rank,b=u.rank,E=`var aIndices: ${c.type.indices};`;for(let T=w-2-1,I=b-1;T>=0;T--,I--)E+=` aIndices[${T}] = ${b>1?`batchIndices[${I}]`:"batchIndices"};`;return d.forEach(T=>{E+=` aIndices[${T}] = 0;`}),E+=` aIndices[${w-2}] = u32(row); aIndices[${w-1}] = u32(colIn);`,E},_=()=>{let w=h.rank,b=u.rank,E=`var bIndices: ${h.type.indices};`;for(let T=w-2-1,I=b-1;T>=0;T--,I--)E+=` bIndices[${T}] = ${b>1?`batchIndices[${I}]`:"batchIndices"};`;return m.forEach(T=>{E+=` bIndices[${T}] = 0;`}),E+=` bIndices[${w-2}] = u32(row); bIndices[${w-1}] = u32(colIn);`,E};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${Hn(n,y)} { var value = ${Hn(n,y)}(0.0); let col = colIn * ${n}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${g()} value = ${c.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${Hn(n,y)} { var value = ${Hn(n,y)}(0.0); let col = colIn * ${n}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${_()} value = ${h.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Hn(n,y)}) { let col = colIn * ${n}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${e?`value = value + ${a?"bias[colIn]":`${Hn(n,y)}(bias[row])`};`:""} ${t} ${p.setByIndices("vec3(coords)","value")} } } `},kd=(n,e,t,r,i=!1)=>{let a=n[0].dims,s=n[1].dims,o=a.slice(0,-2),l=s.slice(0,-2),u=r?r.slice(0,-2):t.slice(0,-2),c=Ee.size(u),h=a[a.length-2],p=a[a.length-1],d=s[s.length-1],m=p%4===0&&d%4===0,y=h<=8?[4,1,1]:[4,4,1],g=[8,8,1],_=[Math.ceil(d/g[0]/y[0]),Math.ceil(h/g[1]/y[1]),Math.ceil(c/g[2]/y[2])],w=m?4:1,b=[...o,h,p/w],E=b.length,T=[...l,p,d/w],I=T.length,C=[c,h,d/w],B=[{type:6,data:h},{type:6,data:d},{type:6,data:p}];ma(e,B),B.push(...gt(u,b,T));let R=["rank","rank"],k=n.length>2;k&&(B.push(...gt(n[2].dims)),R.push("rank")),B.push(...gt(C));let j=Q=>{let ie=u.length,F=Td("batchDims",n[0].dataType,ie,1),$=Rn(n[0].dataType),L=Te("a",n[0].dataType,E,w),H=Te("b",n[1].dataType,I,w),K=ct("result",n[0].dataType,C.length,w),X=[L,H];if(k){let de=i?w:1;X.push(Te("bias",n[2].dataType,n[2].dims.length,de))}let J=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ga(e,J);let W=Rn(K.type.tensor),ae=fa(e,K.type.value,W),Z=Jp(w,k,ae,[F,L,H,K],[o,l,u],i);return` ${Q.registerUniforms(J).registerInternalVariables(F).declareVariables(...X,K)} ${Z} ${m?Ul(y,g,$,F):Bl(y,g,$,F)} `};return{name:"MatMul",shaderCache:{hint:`${y};${e.activation};${m};${i}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:_[0],y:_[1],z:_[2]},programUniforms:B}),getShaderSource:j}}}),ef,Yy,h2=Ce(()=>{bt(),wa(),Ot(),ba(),Id(),Xy(),eu(),ef=(n,e,t,r,i=!1,a,s=4,o=4,l=4,u="f32")=>{let c=R=>{switch(R){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${R} is not supported.`)}},h=R=>{switch(R){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${R} is not supported.`)}},p=n?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,d=n?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,m=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",y=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",g=n?"row":"col",_=n?"col":"row",w=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${g} / outWidth; let outCol = ${g} % outWidth; let WRow = ${_} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${_} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${_} % inChannels; var resData = ${Hn(s,u)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${m} && xCol >= 0 && xCol < ${y}) { ${p} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${c(s)} } return resData;`,b=n?e&&r?` let col = colIn * ${s}; ${w}`:` let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${w} } return ${Hn(s,u)}(0.0);`:r&&t?` let col = colIn * ${s}; ${w}`:` let col = colIn * ${s}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${w} } return ${Hn(s,u)}(0.0);`,E=`${h(o)}`,T=Hn(l,u),I=Hn(n?s:o,u),C=Hn(n?o:s,u),B=fa(a,T,u);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${I} { ${n?b:E} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${C} { ${n?E:b} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${T}) { let col = colIn * ${l}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${d} ${Rd(i)} ${B} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Yy=(n,e,t,r,i,a,s,o)=>{let l=e.format==="NHWC",u=l?n[0].dims[3]:n[0].dims[1],c=t[0],h=l?t[2]:t[3],p=l?t[1]:t[2],d=l?t[3]:t[1],m=l&&(u%4===0||u%3===0)&&d%4===0,y=l?d:h*p,g=l?h*p:d,_=[8,8,1],w=r<=8?[4,1,1]:[4,4,1],b=[Math.ceil(y/_[0]/w[0]),Math.ceil(g/_[1]/w[1]),Math.ceil(c/_[2]/w[2])];mn("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${b}`);let E=m?l&&u%4!==0?3:4:1,T=_[1]*w[1],I=_[0]*w[0],C=Math.max(_[0]*E,_[1]),B=r%T===0,R=i%I===0,k=a%C===0,j=m?[E,4,4]:[1,1,1],Q=[{type:6,data:r},{type:6,data:i},{type:6,data:a},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];ma(e,Q),Q.push(...gt(n[0].dims,n[1].dims));let ie=["rank","rank"];s&&(Q.push(...gt(n[2].dims)),ie.push("rank")),Q.push(...gt(t));let F=$=>{let L=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];ga(e,L);let H=m?4:1,K=Rn(n[0].dataType),X=` fn setOutputAtIndex(flatIndex : i32, value : ${m?`vec4<${K}>`:K}) { result[flatIndex] = ${m?`vec4<${K}>`:K}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${m?`vec4<${K}>`:K}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${m?"/ 4":""}, value); }`,J=Te("x",n[0].dataType,n[0].dims.length,E===3?1:E),W=Te("w",n[1].dataType,n[1].dims.length,H),ae=[J,W],Z=ct("result",n[0].dataType,t.length,H);if(s){let de=Te("bias",n[2].dataType,n[2].dims.length,H);ae.push(de),X+=` fn getBiasByOutputCoords(coords : vec4) -> ${m?`vec4<${K}>`:K} { return bias[coords.${l?"w":"y"}${m?"/ 4":""}]; }`}return` ${Pd("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${$.registerUniforms(L).declareVariables(...ae,Z)} ${X} ${ef(l,B,R,k,s,e,j[0],j[1],j[2],K)} ${m?Ul(w,_,K,void 0,!l,C):Bl(w,_,K,void 0,!l,C,!1,void 0,o)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${E};${m};${B};${R};${k};${T};${I};${C}`,inputDependencies:ie},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:Q}),getShaderSource:F}}}),qc,Ky,p2=Ce(()=>{bt(),Dt(),Ot(),Jy(),ba(),qc=(n,e,t)=>{let r=n.length>2,i=r?"value += b[output_channel];":"",a=n[0].dims,s=n[1].dims,o=s[0]/e.group,l=e.format==="NHWC",u=El(a,s,e.dilations,e.pads,e.strides,l),c=Ee.size(u),h=[{type:12,data:c},{type:12,data:e.dilations},{type:12,data:[e.strides[0],e.strides[1]]},{type:12,data:[e.pads[0],e.pads[1]]},{type:12,data:o}];ma(e,h),h.push(...gt(a,s));let p=["rank","rank"];r&&(h.push(...gt(n[2].dims)),p.push("rank")),h.push(...gt(u));let d=m=>{let y=ct("output",n[0].dataType,u.length),g=Rn(y.type.tensor),_=fa(e,y.type.value,g),w=Te("x",n[0].dataType,a.length),b=Te("w",n[1].dataType,s.length),E=[w,b];r&&E.push(Te("b",n[2].dataType,n[2].dims.length));let T=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:e.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return ga(e,T),` ${m.registerUniforms(T).declareVariables(...E,y)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${y.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${l?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${y.type.value} = ${y.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = group_id * uniforms.w_shape[1] + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[${l?1:2}]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[${l?2:3}]) { continue; } let xVal = ${l?w.get("batch","xHeight","xWidth","input_channel"):w.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${b.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${i} ${_} ${y.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:e.cacheKey,inputDependencies:p},getRunData:()=>({outputs:[{dims:t?t(u):u,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:d}},Ky=(n,e,t)=>{let r=n.length>2,i=vn(t[3]),a=vn(t[2]),s=Ee.size(t)/i/a,o=[n[0].dims[0],n[0].dims[1],n[0].dims[2],n[0].dims[3]/i],l=[n[1].dims[0],n[1].dims[1],n[1].dims[2],n[1].dims[3]/i],u=[t[0],t[1],t[2],t[3]/i],c=[{type:12,data:s},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];ma(e,c),c.push(...gt(o,l,u));let h=(a-1)*e.strides[1]+l[1],p=d=>{let m=ct("output",n[0].dataType,u.length,i),y=Rn(m.type.tensor),g=fa(e,m.type.value,y),_=Te("x",n[0].dataType,o.length,i),w=Te("w",n[1].dataType,l.length,i),b=[_,w];r&&b.push(Te("b",n[2].dataType,n[2].dims,i));let E=r?"value += b[output_channel];":"",T=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ga(e,T),` ${d.registerUniforms(T).declareVariables(...b,m)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${a}u; let col = (index1 % width1) * ${a}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${_.type.value}, ${h}>; var values: array<${m.type.value}, ${a}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${l[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${h}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${_.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${_.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) { let w_val = ${w.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${a}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${a}u; i++) { var value = values[i]; ${E} ${g} ${m.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${i};${a};${h};${l[0]};${l[1]}`,inputDependencies:r?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c}),getShaderSource:p}}}),jc,tf,Zy,Qy=Ce(()=>{bt(),Dt(),eu(),Ot(),ba(),jc=(n,e,t,r,i=!1)=>{let a=n[0].dims,s=n[1].dims,o=a[a.length-2],l=s[s.length-1],u=a[a.length-1],c=vn(l),h=vn(u),p=vn(o),d=Ee.size(t)/c/p,m=n.length>2,y=r?r.slice(0,-2):t.slice(0,-2),g=[Ee.size(y),o,l],_=[{type:12,data:d},{type:12,data:o},{type:12,data:l},{type:12,data:u}];ma(e,_),_.push(...gt(y,a,s)),m&&_.push(...gt(n[2].dims)),_.push(...gt(g));let w=b=>{let E=Td("batch_dims",n[0].dataType,y.length),T=Te("a",n[0].dataType,a.length,h),I=Te("b",n[1].dataType,s.length,c),C=ct("output",n[0].dataType,g.length,c),B=Rn(C.type.tensor),R=fa(e,C.type.value,B),k=[T,I],j="";if(m){let X=i?c:1;k.push(Te("bias",n[2].dataType,n[2].dims.length,X)),j=`${i?`value += bias[col / ${X}];`:`value += ${C.type.value}(bias[row + i]);`}`}let Q=a.slice(0,-2),ie=s.slice(0,-2),F=Ys(Q,y),$=Ys(ie,y),L=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ga(e,L);let H=(X,J)=>{let W=X.rank,ae=X.name;if(W===2)return`var ${ae}_indices = ${X.type.indices}(0u, 0u);`;let Z=E.rank,de=`var ${ae}_indices: ${X.type.indices};`;for(let ye=W-2-1,Pe=Z-1;ye>=0;ye--,Pe--)de+=` ${ae}_indices[${ye}] = ${Z>1?`batch_indices[${Pe}]`:"batch_indices"};`;return J.forEach(ye=>{de+=` ${ae}_indices[${ye}] = 0;`}),de+=`${ae}_indices[${W-2}] = 0u; ${ae}_indices[${W-1}] = 0u;`,de},K=()=>{let X=`var a_data: ${T.type.value};`;for(let J=0;J; for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) { ${K()} } for (var i = 0u; i < ${p}u; i++) { var value = values[i]; ${j} ${R} let cur_indices = ${C.type.indices}(batch, row + i, col); let offset = ${C.indicesToOffset("cur_indices")}; ${C.setByOffset(`offset / ${c}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${c};${h};${p};${i}`,inputDependencies:m?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_}),getShaderSource:w}},tf=n=>{if(!n||n.length!==2)throw new Error("MatMul requires 2 inputs.");if(n[0].dims[n[0].dims.length-1]!==n[1].dims[n[1].dims.length-2])throw new Error("shared dimension does not match.")},Zy=n=>{tf(n.inputs);let e=os.calcShape(n.inputs[0].dims,n.inputs[1].dims,!0);if(!e)throw new Error("Can't use matmul on the given tensors");let t=e[e.length-1],r=n.inputs[0].dims[n.inputs[0].dims.length-1];t<8&&r<8?n.compute(jc(n.inputs,{activation:""},e)):n.compute(kd(n.inputs,{activation:""},e))}}),El,Go,nf,Lu,Xc,rf,af,Yc,Jy=Ce(()=>{Dt(),h2(),eu(),p2(),ba(),Qy(),so(),El=(n,e,t,r,i,a)=>{let s=n[0],o=n.slice(a?1:2,a?3:4),l=o.length,u=e[0],c=e.slice(2).map((p,d)=>p+(p-1)*(t[d]-1)),h=o.map((p,d)=>p+r[d]+r[d+l]).map((p,d)=>Math.floor((p-c[d]+i[d])/i[d]));return h.splice(0,0,s),h.splice(a?3:1,0,u),h},Go=[2,3,1,0],nf=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4&&n[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let t=n[0].dims[e.format==="NHWC"?n[0].dims.length-1:1],r=n[1].dims[1]*e.group;if(t!==r)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(n.length===3&&(n[2].dims.length!==1||n[1].dims[0]!==n[2].dims[0]))throw new Error("invalid bias");let i=n[0].dims.length-2;if(e.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(e.strides.length!==i)throw new Error(`strides should be ${i}D`);if(e.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape")},Lu=(n,e)=>{let t=n.kernelShape.slice();for(let a=2;a{let e=$d(n),t=n.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],i=n.dilations,a=n.group,s=n.kernel_shape,o=n.pads,l=n.strides,u=n.w_is_const();return{autoPad:r,format:t,dilations:i,group:a,kernelShape:s,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${n.format};${e.activation};`}},rf=(n,e,t)=>{let r=Lu(t,e),i=t.format==="NHWC";if(t.group!==1){if(!n.adapterInfo.isArchitecture("ampere")&&i&&e[1].dims[0]===t.group&&e[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1){let I=El(e[0].dims,e[1].dims,t.dilations,r.pads,t.strides,i),C=n.kernelCustomData.wT??n.compute(pi(e[1],Go),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=C);let B=[e[0],C];e.length===3&&B.push(e[2]),n.compute(Ky(B,r,I),{inputs:B})}else n.compute(qc(e,r));return}let a=e.length===3,s=e[0].dims[i?1:2],o=e[0].dims[i?2:3],l=e[0].dims[i?3:1],u=e[1].dims[2],c=e[1].dims[3],h=El(e[0].dims,e[1].dims,t.dilations,r.pads,t.strides,i),p=h[i?1:2],d=h[i?2:3],m=h[i?3:1],y=i&&u===s&&c===o&&t.pads[0]===0&&t.pads[1]===0;if(y||u===1&&c===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let I=h[0],C,B,R,k=[];if(i){let ie=n.kernelCustomData.wT??n.compute(pi(e[1],Go),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=ie),y){let F=s*o*l;C=e[0].reshape([1,I,F]),B=ie.reshape([1,F,m]),R=[1,I,m]}else C=e[0].reshape([I,s*o,l]),B=ie.reshape([1,l,m]),R=[I,p*d,m];k.push(C),k.push(B)}else C=e[0].reshape([I,l,s*o]),B=e[1].reshape([1,m,l]),R=[I,m,p*d],k.push(B),k.push(C);a&&k.push(e[2]);let j=R[2],Q=k[0].dims[k[0].dims.length-1];j<8&&Q<8?n.compute(jc(k,r,h,R,i),{inputs:k}):n.compute(kd(k,r,h,R,i),{inputs:k});return}let g=!0,_=n.kernelCustomData.wT??n.compute(pi(e[1],Go),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=_);let w=[e[0],_];a&&w.push(e[2]);let b=i?p*d:m,E=i?m:p*d,T=u*c*l;n.compute(Yy(w,r,h,b,E,T,a,g),{inputs:w})},af=(n,e)=>{let t=e.format==="NHWC",r=[n.inputs[0].reshape(t?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&r.push(n.inputs[2]);let i=[0,e.pads[0],0,e.pads[1]],a=[1].concat(e.strides),s=[1].concat(e.dilations),o=[1].concat(e.kernelShape),l=Lu({...e,pads:i,strides:a,dilations:s,kernelShape:o},r);n.compute(qc(r,l,u=>t?[u[0],u[2],u[3]]:[]))},Yc=(n,e)=>{nf(n.inputs,e),n.inputs[0].dims.length===3?af(n,e):rf(n,n.inputs,e)}}),sf,ev,f2=Ce(()=>{bt(),wa(),Ot(),ba(),Id(),Xy(),eu(),sf=(n,e=!1,t,r,i=4)=>{let a=g=>{switch(g){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${r}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${g} is not supported.`)}},s=n?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,o=n?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,l=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",u=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",c=n?"row":"col",h=n?"col":"row",p=` let inChannels = ${n?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${c} / outWidth; let outCol = ${c} % outWidth; let WRow = ${h} / (uniforms.filter_dims[1] * inChannels); let WCol = ${h} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${l}) || fract(xR) > 0.0) { return ${r}(0.0); } if (xC < 0.0 || xC >= f32(${u}) || fract(xC) > 0.0) { return ${r}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${h} % inChannels; ${s} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,d=n?` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${p} } return ${r}(0.0);`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${p} } return ${r}(0.0);`,m=` let col = colIn * ${i}; let inChannels = ${n?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${n?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${a(i)} } return ${r}(0.0); `,y=fa(t,r);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${r} { ${n?d:m} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${r} { ${n?m:d} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${r}) { let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${o} ${Rd(e)} ${y} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value; } }`},ev=(n,e,t,r,i,a,s,o)=>{let l=e.format==="NHWC",u=l?n[0].dims[3]:n[0].dims[1],c=t[0],h=l?t[2]:t[3],p=l?t[1]:t[2],d=l?t[3]:t[1],m=l&&u%4===0&&u%3&&d%4===0,y=l?d:h*p,g=l?h*p:d,_=[8,8,1],w=r<=8?[4,1,1]:[4,4,1],b=[Math.ceil(y/_[0]/w[0]),Math.ceil(g/_[1]/w[1]),Math.ceil(c/_[2]/w[2])];mn("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${b}`);let E=m?4:1,T=Math.max(_[0]*E,_[1]),I=m?4:1,C=[e.kernelShape[l?1:2],e.kernelShape[l?2:3]],B=[C[0]+(e.dilations[0]<=1?0:(C[0]-1)*(e.dilations[0]-1)),C[1]+(e.dilations[1]<=1?0:(C[1]-1)*(e.dilations[1]-1))],R=[B[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),B[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],k=[{type:6,data:r},{type:6,data:i},{type:6,data:a},{type:6,data:e.strides},{type:6,data:e.dilations},{type:6,data:C},{type:6,data:R}];ma(e,k),k.push(...gt(n[0].dims,n[1].dims));let j=["rank","rank"];s&&(k.push(...gt(n[2].dims)),j.push("rank")),k.push(...gt(t));let Q=ie=>{let F=Te("x",n[0].dataType,n[0].dims.length,I),$=Te("w",n[1].dataType,n[1].dims.length,1),L=ct("result",n[0].dataType,t.length,I),H=[F,$],K="";if(s){let W=Te("bias",n[2].dataType,n[2].dims.length,I);H.push(W),K+=` fn getBiasByOutputCoords(coords : vec4) -> ${W.type.value} { return bias[coords.${l?"w":"y"}${m?"/ 4":""}]; }`}let X=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:C.length},{name:"pads",type:"i32",length:R.length}];ga(e,X);let J=Rn(n[0].dataType,1);if(J!=="f16"&&J!=="f32")throw new Error(`elemType ${J} is not supported.`);return` ${Pd("uniforms.result_strides")} ${ie.registerUniforms(X).declareVariables(...H,L)}; ${K} ${sf(l,s,e,F.type.value,E)} ${m?Ul(w,_,J,void 0,!l,T):Bl(w,_,J,void 0,!l,T,!1,void 0,o)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${e.cacheKey};${w};${_};${m}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:k}),getShaderSource:Q}}}),of,Kc,m2=Ce(()=>{bt(),wa(),Dt(),Ot(),of=(n,e,t,r,i,a=!1,s,o,l=!1)=>{let u=l?1:2,c=l?2:3,h=l?3:1,p=a?2:1,d=` fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${s}>`:s}) { result[flatIndex] = ${a?`vec4<${s}>`:s}(value); }`;r&&(d+=` fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${s}>`:s} { return bias[coords.${l?"w":"y"}${a?"/ 4":""}]; }`);let m=a?4:1,y=Te("W",e[1].dataType,e[1].dims.length,m),g=Te("Dy",e[0].dataType,e[0].dims.length,m),_=[g,y];r&&_.push(Te("bias",e[2].dataType,[t[h]].length,m));let w=ct("result",e[0].dataType,t.length,m),b=`{ let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${i?"global_id.y":"workgroup_id.y"} * ${p}; let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${p}>; for (var i = 0; i < ${p}; i++) { dotProd[i] = vec4<${s}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${s}(dyCorner.x) + ${s}(wR)) / ${s}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${s}(dyCorner.y) + ${s}(wC)) / ${s}(uniforms.strides.y); let dyC2 = (${s}(dyCorner.y) + 1.0 + ${s}(wC)) / ${s}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${s}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${g.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${g.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${h}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${g.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${g.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${p}; i = i + 1) { let value = dotProd[i] + ${r?"bias[c+i]":`vec4<${s}>(0.0)`}; ${w.set("batch","r","c + i","d1","value")}; } }`,E=` let outputIndices = ${w.offsetToIndices("global_idx")}; let batch = ${w.indicesGet("outputIndices",0)}; let d1 = ${w.indicesGet("outputIndices",h)}; let r = ${w.indicesGet("outputIndices",u)}; let c = ${w.indicesGet("outputIndices",c)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${s}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${u}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${c}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${l?g.get("batch","idyR","idyC","inputChannel"):g.get("batch","inputChannel","idyR","idyC")}; let wValue = ${y.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${r?"bias[d1]":`${s}(0.0)`}; ${w.setByOffset("global_idx","value")}; `;return` ${n.registerUniforms(o).declareVariables(..._,w)} ${d} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${a?b:E}}`},Kc=(n,e,t)=>{let r=n.length>2,i=e.outputShape,a=Ee.size(i),s=[Math.ceil(a/64),1,1];mn("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let o=e.format==="NHWC",l=["rank","rank"],u=[e.strides[0],e.strides[1]],c=[e.kernelShape[o?1:2],e.kernelShape[o?2:3]],h=[e.dilations[0],e.dilations[1]],p=[c[0]+(e.dilations[0]<=1?0:(e.kernelShape[o?1:2]-1)*(e.dilations[0]-1)),c[1]+(e.dilations[1]<=1?0:(e.kernelShape[o?2:3]-1)*(e.dilations[1]-1))],d=[p[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),p[1]-1-Math.floor(e.pads[1]+e.pads[3])/2],m=!1,y=e.group,g=n[1].dims,_=g[0]/y,w=g[1],b=[{type:12,data:a},{type:12,data:u},{type:12,data:c},{type:12,data:h},{type:12,data:p},{type:6,data:d},{type:12,data:_},{type:12,data:w},...gt(n[0].dims,n[1].dims)];r&&(b.push(...gt(n[2].dims)),l.push("rank")),b.push(...gt(i));let E=s[1]===1&&s[2]===1,T=I=>{let C=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:u.length},{name:"filter_dims",type:"u32",length:c.length},{name:"dilations",type:"u32",length:c.length},{name:"effective_filter_dims",type:"u32",length:p.length},{name:"pads",type:"i32",length:d.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],B=Rn(n[0].dataType);return`${of(I,n,i,r,E,m,B,C,o)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:t?t(i):i,dataType:n[0].dataType}],programUniforms:b}),getShaderSource:T}}}),lf,uf,cf,zu,tv,df,hf,pf,ff,nv,g2=Ce(()=>{f2(),m2(),ba(),so(),lf=(n,e,t,r,i,a)=>(n-1)*e+t+(r-1)*i+1-a,uf=(n,e,t,r,i)=>{let a=Math.floor(n/2);e==="SAME_UPPER"?(t[r]=a,t[i]=n-a):e==="SAME_LOWER"&&(t[r]=n-a,t[i]=a)},cf=(n,e,t,r,i,a,s,o,l,u)=>{let c=n.length-2,h=u.length===0;if(l.length===0)for(let m=0;m{let t=n.kernelShape.slice();if(n.kernelShape.length===0||n.kernelShape.reduce((h,p)=>h*p,1)===0){t.length=0;for(let h=2;hh+p,0)===0){let h=e[0].dims.length-2;l=new Array(h).fill(1)}let u=n.strides.slice();if(u.reduce((h,p)=>h+p,0)===0){let h=e[0].dims.length-2;u=new Array(h).fill(1)}cf(o,t,l,n.autoPad,n.group,i,u,r,s,a);let c=Object.assign({},n);return Object.assign(c,{kernelShape:t,pads:i,outputPadding:s,outputShape:a,dilations:l,strides:u}),c},tv=n=>{let e=$d(n),t=n.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof n.autoPad>"u"?0:n.autoPad],i=n.dilations,a=n.group,s=n.kernelShape,o=n.pads,l=n.strides,u=n.wIsConst(),c=n.outputPadding,h=n.outputShape;return{autoPad:r,format:t,dilations:i,group:a,kernelShape:s,outputPadding:c,outputShape:h,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${n.format};${e.activation};`}},df=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4&&n[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let t=n[0].dims[e.format==="NHWC"?n[0].dims.length-1:1],r=n[1].dims[0];if(t!==r)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=n[1].dims[1]*e.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==i))throw new Error("invalid bias");let a=n[0].dims.length-2;if(e.dilations.reduce((s,o)=>s+o,0)>0&&e.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(e.strides.reduce((s,o)=>s+o,0)>0&&e.strides.length!==a)throw new Error(`strides should be ${a}D`);if(e.pads.reduce((s,o)=>s+o,0)>0&&e.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(e.outputPadding.length!==a&&e.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(e.kernelShape.reduce((s,o)=>s+o,0)>0&&e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(e.outputShape.length!==0&&e.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape")},hf=[2,3,1,0],pf=(n,e,t)=>{let r=zu(t,e),i=t.format==="NHWC",a=r.outputShape,s=a[i?3:1],o=e[0].dims[i?3:1];if(r.group!==1||s===1&&o===1){n.compute(Kc(e,r));return}let l=a[i?1:2],u=a[i?2:3],c=e[1].dims[2],h=e[1].dims[3],p=i?l*u:s,d=i?s:l*u,m=c*h*o,y=!0,g=n.kernelCustomData.wT??n.compute(pi(e[1],hf),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=g);let _=[e[0],g],w=e.length===3;w&&(!i&&e[2].dims.length===1?_.push(e[2].reshape([e[2].dims[0],1,1])):_.push(e[2])),n.compute(ev(_,r,a,p,d,m,w,y),{inputs:_})},ff=(n,e)=>{let t=e.format==="NHWC",r=[n.inputs[0].reshape(t?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&r.push(n.inputs[2]);let i=e.kernelShape;(i.length===0||i[0]===0)&&(i=[n.inputs[1].dims[2]]);let a=e.dilations;(a.length===0||a[0]===0)&&(a=[1]);let s=e.strides;(s.length===0||s[0]===0)&&(s=[1]);let o=e.pads;o.length===0&&(o=[0,0]),o=[0,o[0],0,o[1]],s=[1].concat(s),a=[1].concat(a),i=[1].concat(i);let l=zu({...e,pads:o,strides:s,dilations:a,kernelShape:i},r);n.compute(Kc(r,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]]))},nv=(n,e)=>{df(n.inputs,e),n.inputs[0].dims.length===3?ff(n,e):pf(n,n.inputs,e)}}),mf,rv,iv,_2=Ce(()=>{bt(),Dt(),Mn(),Ot(),mf=(n,e,t,r)=>{let i=Ee.size(e),a=e.length,s=Te("input",n,a),o=ct("output",n,a),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=Ee.normalizeAxis(l,a),c=h=>{let p=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,d=Et("uniforms.input_shape","uniforms.axis",a),m=r.reverse?p+(r.exclusive?" + 1":""):"0",y=r.reverse?d:p+(r.exclusive?"":" + 1");return` ${h.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,o)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${o.offsetToIndices("global_idx")}; var sum = ${o.type.value}(0); let first : i32 = ${m}; let last : i32 = ${y}; for (var i : i32 = first; i < last; i++) { ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${s.getByIndices("inputIndices")}; } ${o.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:e,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:u},...gt(e,e)]}),getShaderSource:c}},rv=(n,e)=>{let t=n.inputs[0].dims,r=n.inputs[0].dataType,i=n.inputs[1];n.compute(mf(r,t,i,e),{inputs:[0]})},iv=n=>{let e=n.exclusive===1,t=n.reverse===1;return sn({exclusive:e,reverse:t})}}),gf,_f,yf,av,sv,y2=Ce(()=>{bt(),Dt(),Mn(),Ot(),gf=n=>{if(!n||n.length!==1)throw new Error("DepthToSpace requires 1 input.");if(n[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},_f=(n,e,t,r)=>{let i=[];i.push(`fn perm(i: ${r.type.indices}) -> ${t.type.indices} { var a: ${t.type.indices};`);for(let a=0;a{let t,r,i,a,s,o,l=e.format==="NHWC",u=e.blocksize,c=e.mode==="DCR";l?([t,r,i,a]=n.dims,s=c?[t,r,i,u,u,a/u**2]:[t,r,i,a/u**2,u,u],o=c?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,r,i,a]=[n.dims[0],n.dims[2],n.dims[3],n.dims[1]],s=c?[t,u,u,a/u**2,r,i]:[t,a/u**2,u,u,r,i],o=c?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let h=n.reshape(s),p=h.dims.length,d=n.dataType,m=Te("a",d,p),y=ct("output",d,p),g=_=>` ${_.registerUniform("output_size","u32").declareVariables(m,y)} ${_f(o,p,m,y)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${y.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${y.setByOffset("global_idx",m.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${n.dims};${e.blocksize};${e.mode}`,inputDependencies:["rank"]},getRunData:_=>{let w=l?[t,r*u,i*u,a/u**2]:[t,a/u**2,r*u,i*u],b=Ee.size(w),E=h.dims,T=Ee.sortBasedOnPerm(E,o);return{outputs:[{dims:w,dataType:_[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:12,data:b},...gt(E,T)]}},getShaderSource:g}},av=(n,e)=>{gf(n.inputs),n.compute(yf(n.inputs[0],e))},sv=n=>sn({blocksize:n.blocksize,mode:n.mode,format:n.format})}),Wo,Ts,Nu,vf,wf,bf,xf,Uu,Sf,ov,lv,v2=Ce(()=>{bt(),Dt(),Mn(),Ot(),Wo="[a-zA-Z]|\\.\\.\\.",Ts="("+Wo+")+",Nu="^"+Ts+"$",vf="("+Ts+",)*"+Ts,wf="^"+vf+"$",bf=class{constructor(n=-1){this.symbolToIndices=new Map,this.inputIndex=n}addSymbol(n,e){let t=this.symbolToIndices.get(n);t===void 0?t=[e]:t.push(e),this.symbolToIndices.set(n,t)}},xf=class{constructor(n,e){this.equation=e,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,r]=e.includes("->")?e.split("->",2):[e,""];if(!t.match(RegExp(wf)))throw new Error("Invalid LHS term");if(t.split(",").forEach((i,a)=>{let s=n[a].dims.slice();if(!i.match(RegExp(Nu)))throw new Error("Invalid LHS term");let o=this.processTerm(i,!0,s,a);this.lhs.push(o)}),r==="")r+=[...this.symbolToInfo.entries()].filter(([i,a])=>a.count===1||i==="...").map(([i])=>i).join("");else if(!r.match(RegExp(Ts)))throw new Error("Invalid RHS");r.match(RegExp(Wo,"g"))?.forEach(i=>{if(i==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(i);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(n,e,t){let r=this.symbolToInfo.get(n);if(r!==void 0){if(r.dimValue!==e&&r.count!==1)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(t)}else r={count:1,dimValue:e,inputIndices:[t]};this.symbolToInfo.set(n,r)}processTerm(n,e,t,r=-1){let i=t.length,a=!1,s=[],o=0;if(!n.match(RegExp(Nu))&&!e&&n!=="")throw new Error("Invalid LHS term");let l=n.match(RegExp(Wo,"g")),u=new bf(r);return l?.forEach((c,h)=>{if(c==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let p=i-l.length+1;if(p<0)throw new Error("Ellipsis out of bounds");if(s=t.slice(o,o+p),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else if(e)this.hasEllipsis=!0,this.ellipsisDims=s;else throw new Error("Ellipsis must be specified in the LHS");for(let d=0;dn+"_max",Sf=(n,e,t,r)=>{let i=n.map(u=>u.length).map((u,c)=>Te(`input${c}`,e,u)),a=Ee.size(r),s=ct("output",e,r.length),o=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let c=[],h="var prod = 1.0;",p="var sum = 0.0;",d="sum += prod;",m=[],y=[],g=[],_=[],w=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,T)=>{if(t.rhs.symbolToIndices.has(T)){let I=t.rhs.symbolToIndices.get(T)?.[0];I!==void 0&&t.lhs.forEach((C,B)=>{if(E.inputIndices.includes(B)){let R=C.symbolToIndices.get(T);if(R===void 0)throw new Error("Invalid symbol error");R.forEach(k=>{c.push(`${i[B].indicesSet(`input${B}Indices`,k,s.indicesGet("outputIndices",I))}`)})}})}else t.lhs.forEach((I,C)=>{if(E.inputIndices.includes(C)){let B=I.symbolToIndices.get(T);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(R=>{m.push(`${i[C].indicesSet(`input${C}Indices`,R,`${T}`)}`)}),_.push(`prod *= ${i[C].getByIndices(`input${C}Indices`)};`)}}),y.push(`for(var ${T}: u32 = 0; ${T} < uniforms.${Uu(T)}; ${T}++) {`),g.push("}")});let b=w?[...c,`let sum = ${i.map((E,T)=>E.getByIndices(`input${T}Indices`)).join(" * ")};`]:[...c,p,...y,...m,h,..._,d,...g];return` ${u.registerUniforms(o.map(E=>({name:`${Uu(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,s)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${s.offsetToIndices("global_idx")}; ${i.map((E,T)=>`var input${T}Indices: ${i[T].type.indices};`).join(` `)} ${b.join(` `)}; ${s.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:n.map(()=>"rank")},getRunData:()=>{let u=o.filter(h=>t.symbolToInfo.has(h)).map(h=>({type:12,data:t.symbolToInfo.get(h)?.dimValue||0}));u.push({type:12,data:a});let c=n.map((h,p)=>[...gt(h)]).reduce((h,p)=>h.concat(p),u);return c.push(...gt(r)),{outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}},getShaderSource:l}},ov=(n,e)=>{let t=new xf(n.inputs,e.equation),r=t.outputDims,i=n.inputs.map((a,s)=>a.dims);n.compute(Sf(i,n.inputs[0].dataType,t,r))},lv=n=>{let e=n.equation.replace(/\s+/g,"");return sn({equation:e})}}),Ef,Bu,Mf,Tf,uv,w2=Ce(()=>{bt(),Dt(),Ot(),Ef=n=>{if(!n||n.length!==2)throw new Error("Expand requires 2 input.");let e=n[0].dims,t=Array.from(n[1].getBigInt64Array(),Number),r=t.length{let t=n.length-e.length,r=[];for(let i=0;in.length>e.length?Bu(n,e):Bu(e,n),Tf=n=>{let e=n[0].dims,t=Array.from(n[1].getBigInt64Array(),Number),r=Mf(e,t),i=n[0].dataType,a=i===9?4:1,s=Math.ceil(Ee.size(r)/a),o=u=>{let c=Te("input",i,e.length,a),h=ct("output",i,r.length,a),p;if(i===9){let d=(m,y,g="")=>` let outputIndices${y} = ${h.offsetToIndices(`outputOffset + ${y}u`)}; let offset${y} = ${c.broadcastedIndicesToOffset(`outputIndices${y}`,h)}; let index${y} = offset${y} / 4u; let component${y} = offset${y} % 4u; ${m}[${y}] = ${g}(${c.getByOffset(`index${y}`)}[component${y}]); `;p=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${d("data",0,"u32")} ${d("data",1,"u32")} ${d("data",2,"u32")} ${d("data",3,"u32")} ${h.setByOffset("global_idx","data")} }`}else p=` let outputIndices = ${h.offsetToIndices("global_idx")}; let inputOffset = ${c.broadcastedIndicesToOffset("outputIndices",h)}; ${h.setByOffset("global_idx",c.getByOffset("inputOffset"))} }`;return` ${u.registerUniform("vec_size","u32").declareVariables(c,h)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${p}`},l=[{type:12,data:s},...gt(e,r)];return{name:"Expand",shaderCache:{hint:`${r.length}`,inputDependencies:["rank"]},getShaderSource:o,getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l})}},uv=n=>{Ef(n.inputs),n.compute(Tf(n.inputs),{inputs:[0]})}}),Af,cv,b2=Ce(()=>{bt(),Dt(),Ot(),Cd(),Af=n=>{let e=n[0].dataType,t=Ee.size(n[0].dims),r=Ee.size(n[1].dims),i=r%4===0,a=s=>{let o=Te("x",e,[1],4),l=Te("bias",e,[1],4),u=ct("y",e,[1],4),c=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],h=d=>` let bias${d}_offset: u32 = (global_idx * 4 + ${d}) % uniforms.bias_size; let bias${d} = ${l.getByOffset(`bias${d}_offset / 4`)}[bias${d}_offset % 4];`,p=i?` let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${h(0)}${h(1)}${h(2)}${h(3)} let bias = ${o.type.value}(bias0, bias1, bias2, bias3);`;return`${s.registerUniforms(c).declareVariables(o,l,u)} ${Vc(tr(e))} ${s.mainStart(ls)} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${o.getByOffset("global_idx")}; ${p} let x_in = x + bias; ${u.setByOffset("global_idx",Hc("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:s=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(t/ls/4)}})}},cv=n=>{n.inputs.length<2||Ee.size(n.inputs[1].dims)===0?Oy(n):n.compute(Af(n.inputs))}}),Cf,$f,dv,hv,x2=Ce(()=>{bt(),Dt(),Mn(),Ot(),Cf=n=>{if(!n||n.length!==2)throw new Error("Gather requires 2 inputs.")},$f=(n,e)=>{let t=n[0].dims,r=n[1].dims,i=t.length,a=Ee.normalizeAxis(e.axis,i),s=t.slice(0);s.splice(a,1,...r);let o=t[a],l=n[0].dataType===9?4:1,u=Math.ceil(Ee.size(s)/l),c=[{type:12,data:u},{type:6,data:o},{type:12,data:a},...gt(n[0].dims,n[1].dims,s)],h=p=>{let d=Te("data",n[0].dataType,n[0].dims.length,l),m=Te("inputIndices",n[1].dataType,n[1].dims.length),y=ct("output",n[0].dataType,s.length,l),g=w=>{let b=r.length,E=`var indicesIndices${w} = ${m.type.indices}(0);`;for(let T=0;T1?`indicesIndices${w}[${T}]`:`indicesIndices${w}`} = ${s.length>1?`outputIndices${w}[uniforms.axis + ${T}]`:`outputIndices${w}`};`;E+=` var idx${w} = ${m.getByIndices(`indicesIndices${w}`)}; if (idx${w} < 0) { idx${w} = idx${w} + uniforms.axisDimLimit; } var dataIndices${w} : ${d.type.indices}; `;for(let T=0,I=0;T1?`dataIndices${w}[${T}]`:`dataIndices${w}`} = u32(idx${w});`,I+=b):(E+=`${i>1?`dataIndices${w}[${T}]`:`dataIndices${w}`} = ${s.length>1?`outputIndices${w}[${I}]`:`outputIndices${w}`};`,I++);return E},_;if(n[0].dataType===9){let w=(b,E,T="")=>` let outputIndices${E} = ${y.offsetToIndices(`outputOffset + ${E}u`)}; ${g(E)}; let offset${E} = ${d.indicesToOffset(`dataIndices${E}`)}; let index${E} = offset${E} / 4u; let component${E} = offset${E} % 4u; ${b}[${E}] = ${T}(${d.getByOffset(`index${E}`)}[component${E}]); `;_=` let outputOffset = global_idx * ${l}; var value = vec4(0); ${w("value",0,"u32")} ${w("value",1,"u32")} ${w("value",2,"u32")} ${w("value",3,"u32")} ${y.setByOffset("global_idx","value")} `}else _=` let outputIndices = ${y.offsetToIndices("global_idx")}; ${g("")}; let value = ${d.getByIndices("dataIndices")}; ${y.setByOffset("global_idx","value")}; `;return` ${p.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,m,y)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${_} }`};return{name:"Gather",shaderCache:{hint:e.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}),getShaderSource:h}},dv=n=>sn({axis:n.axis}),hv=(n,e)=>{let t=n.inputs;Cf(t),n.compute($f(n.inputs,e))}}),Rf,If,pv,fv,S2=Ce(()=>{bt(),Dt(),Mn(),Ot(),Rf=n=>{if(!n||n.length!==2)throw new Error("GatherElements requires 2 inputs.");if(n[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(n[0].dims.length!==n[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},If=(n,e)=>{let t=n[0].dims,r=n[0].dataType,i=t.length,a=n[1].dims,s=n[1].dataType,o=Ee.normalizeAxis(e.axis,i),l=t[o],u=a.slice(0),c=Ee.size(u),h=Te("input",r,i),p=Te("indicesInput",s,a.length),d=ct("output",r,u.length),m=[{type:12,data:c},{type:6,data:l},{type:12,data:o}];return m.push(...gt(t,a,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:y=>` ${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(h,p,d)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${d.offsetToIndices("global_idx")}; var idx = ${p.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${h.type.indices}(outputIndices); ${h.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${h.getByIndices("inputIndices")}; ${d.setByOffset("global_idx","value")}; }`}},pv=n=>sn({axis:n.axis}),fv=(n,e)=>{let t=n.inputs;Rf(t),n.compute(If(n.inputs,e))}}),Pf,kf,mv,gv,E2=Ce(()=>{bt(),Dt(),Ot(),Pf=n=>{if(!n)throw new Error("Input is missing");if(n.length<2||n.length>3)throw new Error("Invaid input number.");if(n.length===3&&n[2].dims.length>2)throw new Error("Invalid input shape of C");if(n[0].dataType!==n[1].dataType||n.length===3&&n[0].dataType!==n[2].dataType)throw new Error("Input types are mismatched")},kf=(n,e)=>{let t=n[0].dims.slice(),r=n[1].dims.slice(),[i,a,s]=E0.getShapeOfGemmResult(t,e.transA,r,e.transB,n.length===3?n[2].dims:void 0),o=[i,a];if(!o)throw new Error("Can't use gemm on the given tensors");let l=Ee.size(o),u=[{type:12,data:l},{type:12,data:i},{type:12,data:a},{type:12,data:s},{type:1,data:e.alpha},{type:1,data:e.beta}],c=["type","type"];n.length===3&&(u.push(...gt(n[2].dims)),c.push("rank")),u.push(...gt(o));let h=p=>{let d="";e.transA&&e.transB?d="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":e.transA&&!e.transB?d="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!e.transA&&e.transB?d="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!e.transA&&!e.transB&&(d="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let m=e.alpha===1?"":"value *= uniforms.alpha;",y=Te("a",n[0].dataType,n[0].dims),g=Te("b",n[1].dataType,n[1].dims),_=y.type.value,w=null,b=[y,g];n.length===3&&(w=Te("c",n[2].dataType,n[2].dims.length),b.push(w));let E=ct("output",n[0].dataType,o.length);b.push(E);let T=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${p.registerUniforms(T).declareVariables(...b)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${_}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${d} } ${m} ${w!=null?`let cOffset = ${w.broadcastedIndicesToOffset("vec2(m, n)",E)}; value += ${_}(uniforms.beta) * ${w.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:h}},mv=n=>{let e=n.transA,t=n.transB,r=n.alpha,i=n.beta;return{transA:e,transB:t,alpha:r,beta:i,cacheKey:`${n.transA};${n.transB};${n.alpha===1}`}},gv=(n,e)=>{Pf(n.inputs),n.compute(kf(n.inputs,e))}}),Of,Df,Lf,_v,M2=Ce(()=>{bt(),Dt(),Ot(),Of=(n,e)=>{let t=n[0].dims,r=t,i=2,a=Ee.sizeToDimension(t,i),s=Ee.sizeFromDimension(t,i),o=vn(s),l=s/o,u=[t[0],t[1],l],c=["rank","type","type"],h=[{type:12,data:s},{type:12,data:l}];h.push(...gt(u,u));let p=d=>{let m=Te("x",n[0].dataType,u.length,o),y=Te("scale",n[1].dataType,n[1].dims),g=Te("bias",n[2].dataType,n[2].dims),_=ct("output",n[0].dataType,u.length,o),w=[m,y,g,_],b=m.type.value,E=o===1?"f32":`vec${o}`,T=64,I=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${E}, ${T}>; const workgroupSize = ${T}u; ${d.registerUniforms(I).declareVariables(...w)} ${d.mainStart(T)} let norm = global_idx / workgroupSize; let batch = norm / uniforms.x_shape[1]; let channel = norm % uniforms.x_shape[1]; let localIndex = local_id.x; // initialize workgroup memory var initial = ${E}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${E}(${m.get("batch","channel","h")}); } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the mean of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { meanShared = ${zi("workgroupShared[0]",o)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${E}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${E}(${m.get("batch","channel","h")}) - ${E}(meanShared); initial = initial + deviation * deviation; } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the sum of square of deviation of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { squaredNormShared = ${zi("workgroupShared[0]",o)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); let channelScale = invStdDev * f32(${y.getByOffset("channel")}); let channelShift = f32(${g.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${m.get("batch","channel","h")} * ${b}(${E}(channelScale)) + ${b}(${E}(channelShift)); ${_.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${e.epsilon};${o}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:a},programUniforms:h}),getShaderSource:p}},Df=(n,e,t,r,i,a,s,o)=>{let l=vn(s),u=64,c=l===1?"vec2f":`mat2x${l}f`,h=l===1?"f32":`vec${l}f`,p=(I,C)=>`${c}(${I}, ${C})`,d=i*s/l,m=Math.ceil(a/u),y=["type"],g=[{type:12,data:m},{type:12,data:a},{type:12,data:Math.floor(s/l)},{type:12,data:Math.floor(a*s/l)}],_=I=>{let C=Te("input",e.dataType,e.dims,l);return` ${I.declareVariables(C)} @group(0) @binding(1) var output : array<${c}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${I.mainStart(u)} let currentImageNumber = global_idx / ${u} / uniforms.C; let currentChannelNumber = (global_idx / ${u}) % uniforms.C; let wgOffset = local_id.x * uniforms.wg_size; if (wgOffset >= uniforms.H) { return; } let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; var sum = ${ui("f32",l)}; var squaredSum = ${ui("f32",l)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${h}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${p("sum","squaredSum")}; }`},w=n.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:[i,s,u,2],dataType:1}],dispatchGroup:{x:i*s/l},programUniforms:g}),getShaderSource:_},{inputs:[e],outputs:[-1]})[0],b=[{type:12,data:d},{type:12,data:a},{type:12,data:Math.floor(s/l)},{type:12,data:Math.floor(u*s/l)}],E=["type","type","type"],T=I=>{let C=Te("scale",t.dataType,t.dims,l),B=Te("bias",r.dataType,r.dims,l);return` @group(0) @binding(0) var input : array<${c}>; @group(0) @binding(1) var scale : array<${C.type.storage}>; @group(0) @binding(2) var bias : array<${B.type.storage}>; @group(0) @binding(3) var output : array<${c}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} let currentImageNumber = global_idx / uniforms.C; let currentChannelNumber = global_idx % uniforms.C; let offset = currentImageNumber * uniforms.image_size; var sum = ${ui("f32",l)}; var squaredSum = ${ui("f32",l)}; for (var i: u32 = 0; i < min(${u}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${u}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${o})); let channelScale = invStdDev * ${h}(scale[currentChannelNumber]); let channelShift = ${h}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${p("channelScale","channelShift")}; }`};return n.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:[i,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:b}),getShaderSource:T},{inputs:[w,t,r],outputs:[-1]})[0]},Lf=(n,e,t)=>{let r=e[0].dims,i=r,a=r[0],s=r[r.length-1],o=Ee.sizeFromDimension(r,1)/s,l=vn(s),u=Ee.size(i)/l,c=[{type:12,data:o},{type:12,data:Math.floor(s/l)}],h=["type","type"],p=Df(n,e[0],e[1],e[2],a,o,s,t.epsilon),d=m=>{let y=Rn(e[0].dataType),g=l===1?"vec2f":`mat2x${l}f`,_=l===1?y:`vec${l}<${y}>`,w=Te("input",e[0].dataType,e[0].dims,l),b=ct("output",e[0].dataType,i,l);return` @group(0) @binding(0) var input : array<${w.type.storage}>; @group(0) @binding(1) var scaleInput : array<${g}>; @group(0) @binding(2) var output : array<${b.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${m.mainStart()} let currentImageNumber = global_idx / (uniforms.C * uniforms.H); let currentChannelNumber = global_idx % uniforms.C; let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; let scale = scaleInput[scaleOffset]; output[global_idx] = fma(input[global_idx], ${_}(scale[0]), ${_}(scale[1])); }`};n.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}),getShaderSource:d},{inputs:[e[0],p]})},_v=(n,e)=>{e.format==="NHWC"?Lf(n,n.inputs,e):n.compute(Of(n.inputs,e))}}),zf,Nf,yv,T2=Ce(()=>{bt(),Dt(),Ot(),zf=n=>{if(!n||n.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Nf=(n,e,t)=>{let r=e.simplified,i=n[0].dims,a=n[1],s=!r&&n[2],o=i,l=Ee.normalizeAxis(e.axis,i.length),u=Ee.sizeToDimension(i,l),c=Ee.sizeFromDimension(i,l),h=Ee.size(a.dims),p=s?Ee.size(s.dims):0;if(h!==c||s&&p!==c)throw new Error(`Size of X.shape()[axis:] == ${c}. Size of scale and bias (if provided) must match this. Got scale size of ${h} and bias size of ${p}`);let d=[];for(let T=0;T1,w=t>2,b=T=>{let I=Rn(n[0].dataType),C=[Te("x",n[0].dataType,n[0].dims,m),Te("scale",a.dataType,a.dims,m)];s&&C.push(Te("bias",s.dataType,s.dims,m)),C.push(ct("output",n[0].dataType,o,m)),_&&C.push(ct("mean_data_output",1,d)),w&&C.push(ct("inv_std_output",1,d));let B=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${T.registerUniforms(B).declareVariables(...C)} ${T.mainStart()} ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${ui("f32",m)}; var mean_square_vector = ${ui("f32",m)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${es(I,m,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${zi("mean_vector",m)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${zi("mean_square_vector",m)} / uniforms.norm_size ${r?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${es(I,m,"x[j + offset]")}; let f32scale = ${es(I,m,"scale[j]")}; output[j + offset] = ${C[0].type.value}((f32input ${r?"":"- mean"}) * inv_std_dev * f32scale ${s?`+ ${es(I,m,"bias[j]")}`:""} ); } ${_?"mean_data_output[global_idx] = mean":""}; ${w?"inv_std_output[global_idx] = inv_std_dev":""}; }`},E=[{dims:o,dataType:n[0].dataType}];return _&&E.push({dims:d,dataType:1}),w&&E.push({dims:d,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${m};${t};${r}`,inputDependencies:y},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:g}),getShaderSource:b}},yv=(n,e)=>{zf(n.inputs),n.compute(Nf(n.inputs,e,n.outputCount))}}),Uf,Bf,vv,wv,A2=Ce(()=>{bt(),Dt(),Mn(),Ot(),Uf=(n,e)=>{if(n.length<3||n.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=n[0],r=t.dims.length;if(t.dims[r-1]!==e.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((e.k+e.blockSize-1)/e.blockSize),a=e.blockSize/8*e.bits,s=n[1];if(!Ee.areEqual(s.dims,[e.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=n[2].dims;if(Ee.size(o)!==e.n*i)throw new Error("scales input size error.");if(n.length===4){let l=n[3].dims,u=e.bits>4?e.n*i:e.n*Math.floor((i+1)/2);if(Ee.size(l)!==u)throw new Error("zeroPoints input size error.")}},Bf=(n,e,t,r)=>{let i=n[0].dims,a=i.length,s=Math.floor((e.k+e.blockSize-1)/e.blockSize),o=i[a-2],l=e.k,u=e.n,c=i.slice(0,a-2),h=Ee.size(c),p=e.blockSize/8*e.bits/4,d=n[0].dataType,m=vn(o),y=vn(e.k),g=vn(p),_=Xs(d),w=o*s*_,b=Math.floor(r/w),E=s<=t[0]&&b>0,T=!E||b>=4?vn(u):b>=2&&vn(u)>=2?2:1,I=c.concat([o,u]),C=Ee.size(I)/T/m,B=E?[]:[{type:12,data:C},{type:12,data:e.blockSize}],R=[h,o,l/y],k=Ee.convertShape(n[1].dims).slice();k.splice(-1,1,p/g),B.push(...gt(R)),B.push(...gt(k)),B.push(...gt(n[2].dims)),n.length===4&&B.push(...gt(Ee.convertShape(n[3].dims)));let j=[h,o,u/T];B.push(...gt(j));let Q=ie=>{let F=R.length,$=Te("a",n[0].dataType,F,y),L=Te("b",12,k.length,g),H=Te("scales",n[2].dataType,n[2].dims.length),K=[$,L,H],X=n.length===4?Te("zero_points",12,n[3].dims.length):void 0;X&&K.push(X);let J=j.length,W=ct("output",n[0].dataType,J,T),ae=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],Z=Rn(n[0].dataType),de=(()=>{switch(y){case 1:return`array<${Z}, 8>`;case 2:return`mat4x2<${Z}>`;case 4:return`mat2x4<${Z}>`;default:throw new Error(`${y}-component is not supported.`)}})(),ye=` for (var word: u32 = 0; word < ${p}; word += ${g}) { ${L.indicesSet("b_indices","2","word")}; let b_data = ${L.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${g}; i++) { let b_value: u32 = ${g===1?"b_data":"b_data[word + i]"}; let b_mask: u32 = 0x0F0F0F0Fu; let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); let b_quantized_values = ${de}(${Array.from({length:4},(ke,Be)=>`${Z}(b_value_lower[${Be}]), ${Z}(b_value_upper[${Be}])`).join(", ")}); let b_dequantized_values = ${y===1?`${de}(${Array.from({length:8},(ke,Be)=>`(b_quantized_values[${Be}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${de}(${Array(8).fill("zero_point").join(",")})) * scale;`}; // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 for (var m: u32 = 0; m < ${E?o:m}u; m++) { ${$.indicesSet("a_indices",F-2,E?"m":`row * ${m} + m`)}; ${$.indicesSet("a_indices",F-1,"word_offset")}; var input_offset = ${$.indicesToOffset("a_indices")}; var a_data: ${de}; for (var j: u32 = 0; j < ${8/y}; j++) { a_data[j] = ${$.getByOffset("input_offset")}; input_offset++; } ${E?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${T>1?"[c]":""} += ${Array.from({length:8/y},(ke,Be)=>`${y===1?`a_data[${Be}] * b_dequantized_values[${Be}]`:`dot(a_data[${Be}], b_dequantized_values[${Be}])`}`).join(" + ")}; } word_offset += ${8/y}; } }`,Pe=X?` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${X.getByOffset("zero_point_index")}; }`:"";return E?` var workgroup_shared: array<${W.type.value}, ${o*s}>; ${ie.declareVariables(...K,W)} ${ie.mainStart([s,1,1])} var a_indices: ${$.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${$.indicesSet("a_indices","0","batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${T}; c++) { let col_times_components_plus_c = col * ${T} + c; ${X?` var zero_point_bytes_per_col: u32 = (${s} + 1) / 2; var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; var zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); var zero_point_word: u32 = ${X.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} var b_indices: ${L.type.indices}; ${L.indicesSet("b_indices","0","col_times_components_plus_c")}; // The scale and zero points are computed per block. var scales_index = col_times_components_plus_c * ${s} + block; let scale = ${H.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Z}(${X?"(zero_point_word) & 0xFu":8}); ${L.indicesSet("b_indices","1","block")}; var word_offset: u32 = block * ${e.blockSize/y}; var workgroup_shared_offset: u32 = block * ${o}; ${ye} } workgroupBarrier(); if (local_id.x == 0u) { var output_indices: ${W.type.indices}; ${W.indicesSet("output_indices","0","batch")}; ${W.indicesSet("output_indices",J-1,"col")}; ${W.indicesSet("output_indices",J-2,"0")}; var output_offset = ${W.indicesToOffset("output_indices")}; for (var m: u32 = 0u; m < ${o}u; m++) { var output_value: ${W.type.value} = ${W.type.value}(0); var workgroup_shared_offset: u32 = m; for (var b: u32 = 0u; b < ${s}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${o}; } ${W.setByOffset("output_offset","output_value")}; output_offset += ${u/T}; } } }`:` ${ie.registerUniforms(ae).declareVariables(...K,W)} ${ie.mainStart()} ${ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${W.type.value}, ${m}>; var output_indices = ${W.offsetToIndices("global_idx")}; var col = ${W.indicesGet("output_indices",J-1)}; var row = ${W.indicesGet("output_indices",J-2)}; var a_indices: ${$.type.indices} = output_indices; // Two zero points are packed into one byte because uniforms.bits <= 4. // zero_point_offset is either 0 or 4. It is bit offset within one byte. // TODO support zero_point_offset for bits > 4 ${X?` var zero_point_abs_offset = col * ${T} * ((${s} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${X.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} var scale_index = col * ${s*T}; var b_indices: ${L.type.indices}; for (var c: u32 = 0; c < ${T}; c++) { ${L.indicesSet("b_indices","0",`col * ${T} + c`)}; var block_offset: u32 = 0; for (var block: u32 = 0; block < ${s}; block++) { // The scale and zero points are computed per block. let scale = ${H.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Z}(${X?"extractBits(zero_point_word, zero_point_offset, 4)":8}); ${L.indicesSet("b_indices","1","block")}; var word_offset: u32 = block_offset; ${ye} scale_index++; ${Pe} block_offset += uniforms.block_size / ${y}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${X?`if (zero_point_offset % 8 > 0) { ${Pe} }`:""} } for (var k: u32 = 0u; k < ${m}u; k++) { ${W.indicesSet("output_indices",J-2,`${m} * row + k`)}; ${W.setByIndices("output_indices","output_values[k]")} } }`};return{name:E?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${e.cacheKey};${o};${d};${n.length}`,inputDependencies:Array(n.length).fill("rank")},getRunData:()=>({outputs:[{dims:I,dataType:d}],name:E?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:E?{x:1,y:Math.ceil(u/T),z:h}:{x:Math.ceil(C/64)},programUniforms:B}),getShaderSource:Q}},vv=(n,e)=>{Uf(n.inputs,e);let t=n.getMaxComputeWorkgroupSizes(),r=n.getMaxComputeWorkgroupStoragesize();n.compute(Bf(n.inputs,e,t,r))},wv=n=>sn(n)}),Gn,Ff,bv,Fu,Gf,Vo,xv,C2=Ce(()=>{bt(),Dt(),Mn(),Sd(),ey(),Ot(),so(),Gn=(n,e)=>n.length>e&&n[e].dims.length>0&&Ee.size(n[e].dims)>0?n[e]:void 0,Ff=(n,e)=>{let t=n[0],r=Gn(n,1),i=Gn(n,2),a=Gn(n,3),s=Gn(n,4),o=Gn(n,5),l=Gn(n,6),u=Gn(n,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,h=t.dims[0],p=t.dims[1],d=t.dims.length===3?c?t.dims[2]/3:t.dims[2]:e.numHeads*t.dims[4],m=p,y=0,g=0,_=Math.floor(d/e.numHeads);if(l&&u){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==h||l.dims[1]!==e.numHeads||l.dims[3]!==_)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==h||u.dims[1]!==e.numHeads||u.dims[3]!==_)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');y=l.dims[2],g=l.dims[2]}else if(l||u)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(r){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(r.dims.length===3){if(r.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,m=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==e.numHeads||r.dims[3]!==2||r.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,m=r.dims[1]}else{if(r.dims[1]!==e.numHeads||r.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,m=r.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==e.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(a){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&t.dims.length===5&&t.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let b=0;if(s){b=8;let B=s.dims;throw B.length===1?B[0]===h?b=1:B[0]===3*h+2&&(b=3):B.length===2&&B[0]===h&&B[1]===m&&(b=5),b===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let E=!1,T=d;if(i){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(m!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');T=i.dims[2]}else{if(m!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');T=i.dims[1]*i.dims[3],E=!0}}let I=y+m,C=!1;if(s)throw new Error("Key padding mask is not supported");if(o){if(o.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(o.dims[0]!==h&&o.dims[0]!==1||o.dims[1]!==e.numHeads||o.dims[2]!==p||o.dims[3]!==I)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:h,sequenceLength:p,pastSequenceLength:y,kvSequenceLength:m,totalSequenceLength:I,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:d,vHiddenSize:T,headSize:_,vHeadSize:Math.floor(T/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:b,scale:e.scale,broadcastResPosBias:C,passPastInKv:E,qkvFormat:w}},bv=n=>sn({...n}),Fu=sn({perm:[0,2,1,3]}),Gf=(n,e,t,r,i,a,s)=>{let o=[r,i,a],l=Ee.size(o),u=[{type:12,data:l},{type:12,data:s},{type:12,data:a}],c=h=>{let p=ct("qkv_with_bias",e.dataType,o),d=Te("qkv",e.dataType,o),m=Te("bias",t.dataType,o),y=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${h.registerUniforms(y).declareVariables(d,m,p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return n.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:c},{inputs:[e,t],outputs:[-1]})[0]},Vo=(n,e,t,r,i,a,s,o)=>{let l=a;if(s){if(r===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Gf(n,a,s,e,r,t*i,o),l=l.reshape([e,r,t,i]),n.compute(pi(l,Fu.perm),{inputs:[l],outputs:[-1]})[0]}else return a.dims.length===3&&(l=a.reshape([e,r,t,i])),n.compute(pi(l,Fu.perm),{inputs:[l],outputs:[-1]})[0]},xv=(n,e)=>{let t=Ff(n.inputs,e),r=n.inputs[0],i=Gn(n.inputs,1),a=Gn(n.inputs,2),s=Gn(n.inputs,3),o=Gn(n.inputs,4),l=Gn(n.inputs,5),u=Gn(n.inputs,6),c=Gn(n.inputs,7);if(r.dims.length===5)throw new Error("Packed QKV is not implemented");if(i?.dims.length===5)throw new Error("Packed KV is not implemented");let h=i&&a&&i.dims.length===4&&a.dims.length===4,p=Vo(n,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r,s,0);if(h)return Nl(n,p,i,a,o,void 0,u,c,l,t,e);if(!i||!a)throw new Error("key and value must be provided");let d=Vo(n,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,i,s,t.hiddenSize),m=Vo(n,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,a,s,2*t.hiddenSize);Nl(n,p,d,m,o,void 0,u,c,l,t,e)}}),Wf,Vf,Hf,qf,jf,Xf,Yf,Kf,Sv,$2=Ce(()=>{bt(),Dt(),Ot(),Wf=n=>{if(!n||n.length<1)throw new Error("Too few inputs");if(n[0].dataType!==1&&n[0].dataType!==10)throw new Error("Input type must be float or float16.");if(n.length>=2){let e=n[0].dims.length*2===n[1].dims[0];if(n.length===4&&(e=n[3].dims[0]*2===n[1].dims[0]),!e)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Vf=(n,e,t)=>{let r="";for(let i=e-1;i>=0;--i)r+=` k = i32(${n.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,t)}; if (k < 0) { break; } if (k >= i32(${Et("uniforms.x_shape",i,e)})) { break; } offset += k * i32(${Et("uniforms.x_strides",i,e)}); `;return` value = ${n.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${r} value = x[offset]; } `},Hf=(n,e,t)=>{let r="";for(let i=e-1;i>=0;--i)r+=` k = i32(${n.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,t)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Et("uniforms.x_shape",i,e)}) - 1); k = k % _2n_1; if(k >= i32(${Et("uniforms.x_shape",i,e)})) { k = _2n_1 - k; } } offset += k * i32(${Et("uniforms.x_strides",i,e)}); `;return` var offset = 0; var k = 0; ${r} value = x[offset]; `},qf=(n,e,t)=>{let r="";for(let i=e-1;i>=0;--i)r+=` k = i32(${n.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,t)}; if (k < 0) { k = 0; } if (k >= i32(${Et("uniforms.x_shape",i,e)})) { k = i32(${Et("uniforms.x_shape",i,e)}) - 1; } offset += k * i32(${Et("uniforms.x_strides",i,e)}); `;return` var offset = 0; var k = 0; ${r} value = x[offset]; `},jf=(n,e,t)=>{let r="";for(let i=e-1;i>=0;--i)r+=` k = i32(${n.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,t)}; if (k < 0) { k += i32(${Et("uniforms.x_shape",i,e)}]); } if (k >= i32(${Et("uniforms.x_shape",i,e)})) { k -= i32(${Et("uniforms.x_shape",i,e)}); } offset += k * i32(${Et("uniforms.x_strides",i,e)}); `;return` var offset = 0; var k = 0; ${r} value = x[offset]; `},Xf=(n,e,t)=>{switch(t.mode){case 0:return Vf(n,e,t.pads.length);case 1:return Hf(n,e,t.pads.length);case 2:return qf(n,e,t.pads.length);case 3:return jf(n,e,t.pads.length);default:throw new Error("Invalid mode")}},Yf=(n,e)=>{let t=Ee.padShape(n[0].dims.slice(),e.pads),r=n[0].dims,i=Ee.size(t),a=[{type:12,data:i},{type:6,data:e.pads}];e.mode===0&&a.push({type:n[0].dataType,data:e.value}),a.push(...gt(n[0].dims,t));let s=["rank"],o=l=>{let u=ct("output",n[0].dataType,t.length),c=Te("x",n[0].dataType,r.length),h=c.type.value,p=Xf(u,r.length,e),d=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&d.push({name:"constant_value",type:h}),` ${l.registerUniforms(d).declareVariables(c,u)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${u.offsetToIndices("global_idx")}; var value = ${h}(0); ${p} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${e.mode}`,inputDependencies:s},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(Ee.size(t)/64)},programUniforms:a}),getShaderSource:o}},Kf=(n,e)=>{if(n.length>1){let t=n[1].getBigInt64Array(),r=n.length>=3&&n[2].data?n[2].getFloat32Array()[0]:0,i=n[0].dims.length,a=new Int32Array(2*i).fill(0);if(n.length>=4){let o=n[3].getBigInt64Array();for(let l=0;la[Number(l)]=Number(o));let s=[];return a.forEach(o=>s.push(o)),{mode:e.mode,value:r,pads:s}}else return e},Sv=(n,e)=>{Wf(n.inputs);let t=Kf(n.inputs,e);n.compute(Yf(n.inputs,t),{inputs:[0]})}}),As,Gu,Wu,Vu,Hu,Zf,Qf,qu,ju,Ev,Mv,Xu,Tv,Av,Yu,Cv,$v,Rv,Iv,R2=Ce(()=>{Ur(),bt(),Dt(),Ot(),As=n=>{if(Kt.webgpu.validateInputContent&&(!n||n.length!==1))throw new Error("Pool ops requires 1 input.")},Gu=(n,e,t)=>{let r=e.format==="NHWC",i=n.dims.slice();r&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(e,"dilations"),s=e.kernelShape.slice(),o=e.strides.slice(),l=a?e.dilations.slice():[],u=e.pads.slice();Dl.adjustPoolAttributes(t,i,s,o,l,u);let c=Dl.computePoolOutputShape(t,i,o,l,s,u,e.autoPad),h=Object.assign({},e);a?Object.assign(h,{kernelShape:s,strides:o,pads:u,dilations:l,cacheKey:e.cacheKey}):Object.assign(h,{kernelShape:s,strides:o,pads:u,cacheKey:e.cacheKey});let p=c.slice();return p.push(p.splice(1,1)[0]),[h,r?p:c]},Wu=(n,e)=>{let t=e.format==="NHWC",r=Ee.size(n),i=Ee.size(e.kernelShape),a=[{type:12,data:r},{type:12,data:i}],s=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(e.kernelShape.length<=2){let o=e.kernelShape[e.kernelShape.length-1],l=e.strides[e.strides.length-1],u=e.pads[e.pads.length/2-1],c=e.pads[e.pads.length-1],h=!!(u+c);a.push({type:12,data:o},{type:12,data:l},{type:12,data:u},{type:12,data:c}),s.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let p=!1;if(e.kernelShape.length===2){let d=e.kernelShape[e.kernelShape.length-2],m=e.strides[e.strides.length-2],y=e.pads[e.pads.length/2-2],g=e.pads[e.pads.length-2];p=!!(y+g),a.push({type:12,data:d},{type:12,data:m},{type:12,data:y},{type:12,data:g}),s.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,s,!0,h,p]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let o=Ee.computeStrides(e.kernelShape);a.push({type:12,data:o},{type:12,data:e.pads},{type:12,data:e.strides}),s.push({name:"kernelStrides",type:"u32",length:o.length},{name:"pads",type:"u32",length:e.pads.length},{name:"strides",type:"u32",length:e.strides.length});let l=e.pads.reduce((u,c)=>u+c);return[a,s,!!l,!1,!1]}},Vu=(n,e,t,r,i,a,s,o,l,u,c,h)=>{let p=i.format==="NHWC",d=e.type.value,m=ct("output",e.type.tensor,r);if(i.kernelShape.length<=2){let y="",g="",_="",w=t-(p?2:1);if(c?y=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${w}] = indices[${w}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${w}] < 0 || xIndices[${w}] >= uniforms.x_shape[${w}]) { pad++; continue; } let x_val = x[${e.indicesToOffset("xIndices")}]; ${a} }`:y=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${w}] = indices[${w}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${e.indicesToOffset("xIndices")}]; ${a} }`,i.kernelShape.length===2){let b=t-(p?3:2);h?g=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${b}] = indices[${b}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${b}] < 0 || xIndices[${b}] >= uniforms.x_shape[${b}]) { pad += i32(uniforms.kw); continue; } `:g=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${b}] = indices[${b}] * uniforms.sh - uniforms.phStart + j; `,_=` } `}return` ${n.registerUniforms(l).declareVariables(e,m)} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${m.offsetToIndices("global_idx")}; var xIndices = ${m.offsetToIndices("global_idx")}; var value = ${d}(${o}); var pad = 0; ${g} ${y} ${_} ${s} output[global_idx] = value; }`}else{if(p)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let y=i.kernelShape.length,g=i.pads.length,_="";return u?_=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${e.indicesToOffset("xIndices")}]; ${a} }`:_=` } let x_val = x[${e.indicesToOffset("xIndices")}]; ${a} `,` ${n.registerUniforms(l).declareVariables(e,m)} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${m.offsetToIndices("global_idx")}; var xIndices = ${m.offsetToIndices("global_idx")}; var offsets: array; var value = ${d}(${o}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${y-1}u; j++) { offsets[j] = offset / ${Et("uniforms.kernelStrides","j",y)}; offset -= offsets[j] * ${Et("uniforms.kernelStrides","j",y)}; } offsets[${y-1}] = offset; isPad = false; for (var j = ${t-y}u; j < ${t}u; j++) { xIndices[j] = indices[j] * ${Et("uniforms.strides",`j - ${t-y}u`,y)} + offsets[j - ${t-y}u] - ${Et("uniforms.pads","j - 2u",g)}; ${_} } ${s} output[global_idx] = value; }`}},Hu=n=>`${n.format};${n.ceilMode};${n.autoPad};${n.kernelShape.length}`,Zf=n=>`${Hu(n)};${n.countIncludePad}`,Qf=n=>`${Hu(n)};${n.storageOrder};${n.dilations}`,qu=n=>({format:n.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],ceilMode:n.ceil_mode,kernelShape:n.kernel_shape,strides:n.strides,pads:n.pads}),ju=(n,e,t,r)=>{let[i,a]=Gu(e,r,t),s=Te("x",e.dataType,e.dims.length),o=s.type.value,l="value += x_val;",u="";i.countIncludePad?u+=`value /= ${o}(uniforms.kernelSize);`:u+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[c,h,p,d,m]=Wu(a,i);c.push(...gt(e.dims,a));let y=["rank"];return{name:n,shaderCache:{hint:`${r.cacheKey};${p};${d};${m}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(Ee.size(a)/64)},programUniforms:c}),getShaderSource:g=>Vu(g,s,e.dims.length,a.length,i,l,u,0,h,p,d,m)}},Ev=n=>{let e=n.count_include_pad!==0,t=qu(n);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let r={countIncludePad:e,...t,cacheKey:""};return{...r,cacheKey:Zf(r)}},Mv=(n,e)=>{As(n.inputs),n.compute(ju("AveragePool",n.inputs[0],!1,e))},Xu={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Tv=n=>{let e=n.format;return{format:e,...Xu,cacheKey:e}},Av=(n,e)=>{As(n.inputs),n.compute(ju("GlobalAveragePool",n.inputs[0],!0,e))},Yu=(n,e,t,r)=>{let[i,a]=Gu(e,r,t),s=` value = max(x_val, value); `,o="",l=Te("x",e.dataType,e.dims.length),u=["rank"],[c,h,p,d,m]=Wu(a,i);return c.push(...gt(e.dims,a)),{name:n,shaderCache:{hint:`${r.cacheKey};${p};${d};${m}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(Ee.size(a)/64)},programUniforms:c}),getShaderSource:y=>Vu(y,l,e.dims.length,a.length,i,s,o,e.dataType===10?-65504:-1e5,h,p,d,m)}},Cv=(n,e)=>{As(n.inputs),n.compute(Yu("MaxPool",n.inputs[0],!1,e))},$v=n=>{let e=n.storage_order,t=n.dilations,r=qu(n);if(e!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:e,dilations:t,...r,cacheKey:""};return{...i,cacheKey:Qf(i)}},Rv=n=>{let e=n.format;return{format:e,...Xu,cacheKey:e}},Iv=(n,e)=>{As(n.inputs),n.compute(Yu("GlobalMaxPool",n.inputs[0],!0,e))}}),Jf,em,Pv,I2=Ce(()=>{Ur(),bt(),Ot(),Jf=(n,e,t)=>{let r=n===e,i=ne&&t>0;if(r||i||a)throw new Error("Range these inputs' contents are invalid.")},em=(n,e,t,r)=>{let i=Math.abs(Math.ceil((e-n)/t)),a=[i],s=i,o=[{type:12,data:s},{type:r,data:n},{type:r,data:t},...gt(a)],l=u=>{let c=ct("output",r,a.length),h=c.type.value,p=[{name:"outputSize",type:"u32"},{name:"start",type:h},{name:"delta",type:h}];return` ${u.registerUniforms(p).declareVariables(c)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${h}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:a,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},Pv=n=>{let e=0,t=0,r=0;n.inputs[0].dataType===6?(e=n.inputs[0].getInt32Array()[0],t=n.inputs[1].getInt32Array()[0],r=n.inputs[2].getInt32Array()[0]):n.inputs[0].dataType===1&&(e=n.inputs[0].getFloat32Array()[0],t=n.inputs[1].getFloat32Array()[0],r=n.inputs[2].getFloat32Array()[0]),Kt.webgpu.validateInputContent&&Jf(e,t,r),n.compute(em(e,t,r,n.inputs[0].dataType),{inputs:[]})}}),tm,nm,rm,im,am,sm,om,lm,um,cm,dm,Ku,hm,pm,fm,mm,gm,kv,Ov,P2=Ce(()=>{bt(),Dt(),Mn(),Ot(),tm=(n,e)=>{if(n.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),n.length>0){if(e.mode==="linear"){if(!(n.length===2||n.length===3||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1||n.length===5&&n[0]===1&&n[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(e.mode==="cubic"&&!(n.length===2||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},nm=(n,e,t)=>{e.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let r=new Array(t).fill(1);return e.forEach((i,a)=>r[i]=n[a]),r},rm=(n,e,t,r,i,a)=>{let[s,o,l]=t>10?[1,2,3]:[-1,n.length>1?1:-1,-1],u=n[0].dims.length;if(s>0&&n.length>s&&n[s].dims.length>0)n[s].getFloat32Array().forEach(c=>a.push(c));else if(e.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&n.length>o&&n[o].dims.length>0){if(n[o].getFloat32Array().forEach(c=>r.push(c)),r.length!==0&&r.length!==u&&t>=18&&r.length!==e.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");tm(r,e),e.axes.length>0&&nm(r,e.axes,u).forEach((c,h)=>r[h]=c)}if(l>0&&n.length>l&&(n[l].getBigInt64Array().forEach(c=>i.push(Number(c))),i.length!==u||t>=18&&i.length===e.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(e.axes.length>0){if(r.length!==e.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==e.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof r<"u"&&typeof i<"u"&&r.length>0&&i.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},im=(n,e)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${e} { `+(()=>{switch(n){case"asymmetric":return`return ${e}(xResized) / ${e}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${e}(xResized) + 0.5) / ${e}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${e}(xResized) + 0.5) / ${e}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${e}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${e}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${e}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${e}(roiStart) * ${e}(lengthOriginal - 1) + (${e}(xResized) * ${e}(roiEnd - roiStart) * ${e}(lengthOriginal - 1)) / ${e}(lengthResized - 1); } else { return 0.5 * ${e}(roiStart + roiEnd) * ${e}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${e}xScale * ${e}(lengthResized); const adjustment = ${e}(lengthResized) / outputWidth; const center = ${e}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;case"half_pixel":return`return ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${n} is not supported`)}})()+"}",am=(n,e,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(n){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(e<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${n} is not supported`)}})()+"}",sm=(n,e,t)=>{let r=new Array(t).fill(0).concat(new Array(t).fill(1)),i=n.length===0?r:n.slice();return e.length>0?(e.forEach((a,s)=>{r[a]=i[s],r[s+t]=i[e.length+s]}),r):i},om=(n,e,t,r)=>{let i=[];if(t.length>0)if(r.length>0){if(n.forEach(a=>i.push(a)),Math.max(...r)>n.length)throw new Error("axes is out of bound");r.forEach((a,s)=>i[a]=t[s])}else t.forEach(a=>i.push(a));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");i=n.map((a,s)=>Math.round(a*e[s]))}return i},lm=(n,e,t)=>{let r=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(a=>e[a]),Number.MAX_VALUE):Math.min(...e,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(a=>e[a]),Number.MIN_VALUE):Math.max(...e,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();e.fill(1,0,e.length);let i=n.slice();return t.axes.length>0?(t.axes.forEach(a=>e[a]=r),t.axes.forEach(a=>i[a]=Math.round(n[a]*e[a]))):(e.fill(r,0,e.length),i.forEach((a,s)=>i[s]=Math.round(a*e[s]))),i},um=(n,e,t,r,i)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${n.type.indices}) -> array<${n.type.value}, ${t.length}> { var original_indices: array<${n.type.value}, ${t.length}>; for (var i:u32 = 0; i < ${t.length}; i++) { var output_index = ${n.indicesGet("output_indices","i")}; var scale = ${Et("uniforms.scales","i",r)}; var roi_low = ${Et("uniforms.roi","i",i)}; var roi_hi = ${Et("uniforms.roi",`i + ${e.length}`,i)}; if (scale == 1.0) { original_indices[i] = ${n.type.value}(output_index); } else { var input_shape_i = ${Et("uniforms.input_shape","i",e.length)}; var output_shape_i = ${Et("uniforms.output_shape","i",t.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,cm=(n,e,t,r,i,a,s)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> ${n.type.indices} { var input_indices: ${n.type.indices}; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Et("uniforms.scales","i",i)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Et("uniforms.roi","i",a)}; var roi_hi = ${Et("uniforms.roi",`i + ${t.length}`,a)}; var input_shape_i = ${Et("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Et("uniforms.output_shape","i",r.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${s} || (original_idx >= 0 && original_idx < ${e.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${e.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${n.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,dm=(n,e)=>` fn checkInputIndices(input_indices: ${n.type.indices}) -> bool { for (var i:u32 = 0; i < ${e.length}; i++) { var input_index = ${n.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${Et("uniforms.input_shape","i",e.length)}) { return false; } } return true; }`,Ku=(n,e,t,r)=>n.rank>r?` ${n.indicesSet("input_indices",e,"channel")}; ${n.indicesSet("input_indices",t,"batch")}; `:"",hm=(n,e,t,r,i)=>{let[a,s,o,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=n.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { var input_indices: ${n.type.indices}; ${n.indicesSet("input_indices",s,`max(0, min(row, ${t[s]} - 1))`)}; ${n.indicesSet("input_indices",o,`max(0, min(col, ${t[o]} - 1))`)}; ${Ku(n,l,a,2)} return ${n.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${e.type.indices}) -> ${u} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${u} = originalIndices[${s}]; var col:${u} = originalIndices[${o}]; ${r?`if (row < 0 || row > (${t[s]} - 1) || col < 0 || col > (${t[o]} - 1)) { return ${i}; }`:""}; row = max(0, min(row, ${t[s]} - 1)); col = max(0, min(col, ${t[o]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; var batch: u32 = ${t.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${u} = getInputValue(batch, channel, row1, col1); var x12: ${u} = getInputValue(batch, channel, row1, col2); var x21: ${u} = getInputValue(batch, channel, row2, col1); var x22: ${u} = getInputValue(batch, channel, row2, col2); var dx1: ${u} = abs(row - ${u}(row1)); var dx2: ${u} = abs(${u}(row2) - row); var dy1: ${u} = abs(col - ${u}(col1)); var dy2: ${u} = abs(${u}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},pm=(n,e,t,r,i,a,s,o,l,u)=>{let c=t.length===2,[h,p]=c?[0,1]:[2,3],d=n.type.value,m=y=>{let g=y===h?"row":"col";return` fn ${g}CubicInterpolation(input_indices: ${n.type.indices}, output_indices: ${e.type.indices}) -> ${d} { var output_index = ${e.indicesGet("output_indices",y)}; var originalIdx: ${d} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[y]}, ${r[y]}, ${t[y]}, ${a[y]}, ${a[y]} + ${t.length}); var fractOriginalIdx: ${d} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${o} && (originalIdx < 0 || originalIdx > (${t[y]} - 1))) { return ${l}; } var data: array<${d}, 4> = array<${d}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${g}: ${d} = originalIdx + ${d}(i); if (${g} < 0 || ${g} >= ${t[y]}) { ${u?`coefs[i + 1] = 0.0; continue;`:o?`return ${l};`:`${g} = max(0, min(${g}, ${t[y]} - 1));`}; } var input_indices_copy: ${n.type.indices} = input_indices; ${n.indicesSet("input_indices_copy",y,`u32(${g})`)}; data[i + 1] = ${y===h?n.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${m(h)}; ${m(p)}; fn getCubicInterpolationCoefs(s: ${d}) -> array<${d}, 4> { var absS = abs(s); var coeffs: array<${d}, 4> = array<${d}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${d} = 1.0 - absS; var twoMinusAbsS: ${d} = 2.0 - absS; var onePlusAbsS: ${d} = 1.0 + absS; coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s}; coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1; coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s}; return coeffs; } fn cubicInterpolation1D(x: array<${d}, 4>, coefs: array<${d}, 4>) -> ${d} { var coefsSum: ${d} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${e.type.indices}) -> ${d} { var input_indices: ${n.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},fm=(n,e,t,r,i)=>{let[a,s,o,l,u]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],c=n.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${c} { var input_indices: ${n.type.indices}; ${n.indicesSet("input_indices",s,`max(0, min(depth, ${t[s]} - 1))`)}; ${n.indicesSet("input_indices",o,`max(0, min(height, ${t[o]} - 1))`)}; ${n.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; ${Ku(n,u,a,3)} return ${n.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${c} = originalIndices[${s}]; var height:${c} = originalIndices[${o}]; var width:${c} = originalIndices[${l}]; ${r?`if (depth < 0 || depth > (${t[s]} - 1) || height < 0 || height > (${t[o]} - 1) || width < 0 || (width > ${t[l]} - 1)) { return ${i}; }`:""}; depth = max(0, min(depth, ${t[s]} - 1)); height = max(0, min(height, ${t[o]} - 1)); width = max(0, min(width, ${t[l]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${t.length>3?`u32(originalIndices[${u}])`:"0"}; var batch: u32 = ${t.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${c} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${c} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${c} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${c} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${c} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${c} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${c} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${c} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${c} = abs(depth - ${c}(depth1)); var dx2: ${c} = abs(${c}(depth2) - depth); var dy1: ${c} = abs(height - ${c}(height1)); var dy2: ${c} = abs(${c}(height2) - height); var dz1: ${c} = abs(width - ${c}(width1)); var dz2: ${c} = abs(${c}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},mm=(n,e,t,r,i,a)=>{let s=n.dims,o=sm(a,e.axes,s.length),l=om(s,r,i,e.axes),u=r.slice();r.length===0&&(u=s.map((w,b)=>w===0?1:l[b]/w),e.keepAspectRatioPolicy!=="stretch"&&(l=lm(s,u,e)));let c=ct("output",n.dataType,l.length),h=Te("input",n.dataType,s.length),p=Ee.size(l),d=s.length===l.length&&s.every((w,b)=>w===l[b]),m=e.coordinateTransformMode==="tf_crop_and_resize",y=e.extrapolationValue,g=h.type.value,_=w=>` ${d?"":` ${im(e.coordinateTransformMode,g)}; ${(()=>{switch(e.mode){case"nearest":return` ${dm(h,s)}; ${am(e.nearestMode,t,g)}; ${cm(h,c,s,l,u.length,o.length,m)}; `;case"linear":return` ${um(c,s,l,u.length,o.length)}; ${(()=>{if(s.length===2||s.length===4)return`${hm(h,c,s,m,y)}`;if(s.length===3||s.length===5)return`${fm(h,c,s,m,y)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(s.length===2||s.length===4)return`${pm(h,c,s,l,u,o,e.cubicCoeffA,m,e.extrapolationValue,e.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${w.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",o.length).declareVariables(h,c)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${d?"output[global_idx] = input[global_idx];":` let output_indices = ${c.offsetToIndices("global_idx")}; var input_indices: ${h.type.indices}; ${(()=>{switch(e.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${h.getByIndices("input_indices")}; } else { output[global_idx] = ${e.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${s.length===2||s.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${e.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${e.cacheKey}|${t}|${u.length>0?u:""}|${i.length>0?i:""}|${o.length>0?o:""}|${d}|${s}`,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:l,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:1,data:u},{type:1,data:o},...gt(s,l)]})}},gm=n=>{let e=n.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},kv=(n,e)=>{let t=[],r=[],i=[],a=gm(n);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");rm(n.inputs,e,a,t,r,i),n.compute(mm(n.inputs[0],e,a,t,r,i),{inputs:[0]})},Ov=n=>{let e=n.antialias,t=n.axes,r=n.coordinateTransformMode,i=n.cubicCoeffA,a=n.excludeOutside!==0,s=n.extrapolationValue,o=n.keepAspectRatioPolicy,l=n.mode,u=n.nearestMode===""?"simple":n.nearestMode;return sn({antialias:e,axes:t,coordinateTransformMode:r,cubicCoeffA:i,excludeOutside:a,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:u})}}),_m,ym,Dv,k2=Ce(()=>{bt(),Dt(),Mn(),Ot(),_m=(n,e)=>{let[t,r,i,a]=n,{numHeads:s,rotaryEmbeddingDim:o}=e;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!Ee.areEqual(r.dims,[])&&!Ee.areEqual(r.dims,[1])&&r.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${r.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Ee.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(o>0&&s===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],u=t.dims[t.dims.length-2],c=i.dims[0],h=Ee.sizeFromDimension(t.dims,1)/u,p=o===0?i.dims[1]*2:h/s;if(o>p)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(r.dims.length===2){if(l!==r.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${r.dims[0]}`);if(u!==r.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${r.dims[1]}`)}if(p/2!==i.dims[1]&&o/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(u>c)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ym=(n,e)=>{let{interleaved:t,numHeads:r,rotaryEmbeddingDim:i,scale:a}=e,s=n[0].dims[0],o=Ee.sizeFromDimension(n[0].dims,1),l=n[0].dims[n[0].dims.length-2],u=o/l,c=n[2].dims[1],h=i===0?c*2:u/r,p=new Array(s,l,u/h,h-c),d=Ee.computeStrides(p),m=[{type:1,data:a},{type:12,data:p},{type:12,data:d},...n[0].dims.length===3?new Array({type:12,data:[o,u,h,1]}):[],...n[0].dims.length===4?new Array({type:12,data:[o,h,l*h,1]}):[],...gt(n[0].dims,n[1].dims,n[2].dims,n[3].dims,n[0].dims)],y=g=>{let _=Te("input",n[0].dataType,n[0].dims.length),w=Te("position_ids",n[1].dataType,n[1].dims.length),b=Te("cos_cache",n[2].dataType,n[2].dims.length),E=Te("sin_cache",n[3].dataType,n[3].dims.length),T=ct("output",n[0].dataType,n[0].dims.length);return g.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:p.length},{name:"global_strides",type:"u32",length:d.length},{name:"input_output_strides",type:"u32",length:d.length}]),` ${g.declareVariables(_,w,b,E,T)} ${g.mainStart(ls)} let half_rotary_emb_dim = uniforms.${b.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${g.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${w.broadcastedIndicesToOffset("bsnh.xy",ct("",w.type.tensor,2))}; let position_id = u32(${w.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); let j = i + select(half_rotary_emb_dim, 1, ${t}); let re = ${_.getByOffset("i")} * ${b.get("position_id","bsnh[3]")} - ${_.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; ${T.setByOffset("i","re")} let im = ${_.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + ${_.getByOffset("j")} * ${b.get("position_id","bsnh[3]")}; ${T.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${T.setByOffset("k",_.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:sn({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(Ee.size(p)/ls)},programUniforms:m})}},Dv=(n,e)=>{_m(n.inputs,e),n.compute(ym(n.inputs,e))}}),vm,wm,Lv,O2=Ce(()=>{bt(),Dt(),Ot(),vm=n=>{if(!n||n.length<3)throw new Error("layerNorm requires at least 3 inputs.");let e=n[0],t=n[1],r=n[2];if(e.dataType!==t.dataType||e.dataType!==r.dataType)throw new Error("All inputs must have the same data type");if(e.dims.length!==3&&e.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=e.dims[e.dims.length-1],a=e.dims[e.dims.length-2];if(t.dims[t.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(r.dims.length!==1)throw new Error("Gamma must be 1D");if(r.dims[r.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(n.length>3){let s=n[3];if(s.dims.length!==1)throw new Error("Beta must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(n.length>4){let s=n[4];if(s.dims.length!==1)throw new Error("Bias must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},wm=(n,e,t,r)=>{let i=e.simplified,a=n[0].dims,s=Ee.size(a),o=a,l=s,u=a.slice(-1)[0],c=r?a.slice(0,-1).concat(1):[],h=!i&&n.length>3,p=n.length>4,d=r&&t>1,m=r&&t>2,y=t>3,g=vn(u),_=[{type:12,data:l},{type:12,data:g},{type:12,data:u},{type:1,data:e.epsilon}],w=E=>{let T=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],I=[Te("x",n[0].dataType,n[0].dims,g),Te("skip",n[1].dataType,n[1].dims,g),Te("gamma",n[2].dataType,n[2].dims,g)];h&&I.push(Te("beta",n[3].dataType,n[3].dims,g)),p&&I.push(Te("bias",n[4].dataType,n[4].dims,g)),I.push(ct("output",n[0].dataType,o,g)),d&&I.push(ct("mean_output",1,c)),m&&I.push(ct("inv_std_output",1,c)),y&&I.push(ct("input_skip_bias_sum",n[0].dataType,o,g));let C=Rn(n[0].dataType);return` ${E.registerUniforms(T).declareVariables(...I)} ${E.mainStart()} ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")} let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; let offset = global_idx * hidden_size_vectorized; var sum = ${ui("f32",g)}; var squareSum = ${ui("f32",g)}; for (var i: u32 = 0; i < hidden_size_vectorized; i++) { let skip_value = skip[offset + i]; let bias_value = ${p?"bias[i]":C+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${y?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${es(C,g,"value")}; sum += f32_value; squareSum += f32_value * f32_value; } let mean = ${zi("sum",g)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${zi("squareSum",g)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); ${d?"mean_output[global_idx] = mean;":""} ${m?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < hidden_size_vectorized; i++) { output[offset + i] = (output[offset + i] ${i?"":`- ${C}(mean)`}) * ${C}(inv_std_dev) * gamma[i] ${h?"+ beta[i]":""}; } }`},b=[{dims:o,dataType:n[0].dataType}];return t>1&&b.push({dims:c,dataType:1}),t>2&&b.push({dims:c,dataType:1}),t>3&&b.push({dims:a,dataType:n[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${g};${d};${m};${y}`,inputDependencies:n.map((E,T)=>"type")},getShaderSource:w,getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(l/u/64)},programUniforms:_})}},Lv=(n,e)=>{vm(n.inputs);let t=[0];n.outputCount>1&&t.push(-3),n.outputCount>2&&t.push(-3),n.outputCount>3&&t.push(3),n.compute(wm(n.inputs,e,n.outputCount,!1),{outputs:t})}}),bm,Cs,xm,Zu,Sm,Em,zv,Nv,D2=Ce(()=>{bt(),Dt(),Mn(),Ot(),bm=(n,e)=>{if(!n||n.length<1)throw new Error("too few inputs");if(e.axes.length!==0){if(e.axes.length!==e.starts.length||e.axes.length!==e.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(e.starts.length!==e.ends.length)throw new Error("starts and ends must have the same length");n.slice(1).forEach((t,r)=>{if(n[r+1].dataType!==6&&n[r+1].dataType!==7)throw new Error(`Input ${r} must be an array of int32 or int64`)})},Cs=(n,e)=>{let t=[];if(n.length>e)if(n[e].dataType===7)n[e].getBigInt64Array().forEach(r=>t.push(Number(r)));else if(n[e].dataType===6)n[e].getInt32Array().forEach(r=>t.push(Number(r)));else throw new Error(`Input ${e} must be an array of int32 or int64`);return t},xm=(n,e)=>{if(n.length>1){let t=Cs(n,1),r=Cs(n,2),i=Cs(n,3);return i.length===0&&(i=[...Array(n[0].dims.length).keys()]),sn({starts:t,ends:r,axes:i})}else return e},Zu=(n,e,t,r,i)=>{let a=n;return n<0&&(a+=t[r[e]]),i[e]<0?Math.max(0,Math.min(a,t[r[e]]-1)):Math.max(0,Math.min(a,t[r[e]]))},Sm=(n,e,t)=>`fn calculateInputIndices(output_indices: ${e.type.indices}) -> ${n.type.indices} { var input_indices: ${n.type.indices}; var carry = 0u; for (var i = ${t.length}; i >= 0; i--) { let input_shape_i = ${Et("uniforms.input_shape","i",t.length)}; let steps_i = ${Et("uniforms.steps","i",t.length)}; let signs_i = ${Et("uniforms.signs","i",t.length)}; let starts_i = ${Et("uniforms.starts","i",t.length)}; var output_index = ${e.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${n.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,Em=(n,e)=>{let t=n[0].dims,r=Ee.size(t),i=e.axes.length>0?Ee.normalizeAxes(e.axes,t.length):[...Array(t.length).keys()],a=Cs(n,4);a.forEach(_=>_!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let s=e.starts.map((_,w)=>Zu(_,w,t,i,a)),o=e.ends.map((_,w)=>Zu(_,w,t,i,a));if(i.length!==s.length||i.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==t.length)for(let _=0;_Math.sign(_));a.forEach((_,w,b)=>{if(_<0){let E=(o[w]-s[w])/_,T=s[w],I=T+E*a[w];s[w]=I,o[w]=T,b[w]=-_}});let u=t.slice(0);i.forEach((_,w)=>{u[_]=Math.ceil((o[_]-s[_])/a[_])});let c={dims:u,dataType:n[0].dataType},h=ct("output",n[0].dataType,u.length),p=Te("input",n[0].dataType,n[0].dims.length),d=Ee.size(u),m=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:a.length}],y=[{type:12,data:d},{type:12,data:s},{type:6,data:l},{type:12,data:a},...gt(n[0].dims,u)],g=_=>` ${_.registerUniforms(m).declareVariables(p,h)} ${Sm(p,h,t)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${h.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${h.setByOffset("global_idx",p.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${s.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:g,getRunData:()=>({outputs:[c],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:y})}},zv=(n,e)=>{bm(n.inputs,e);let t=xm(n.inputs,e);n.compute(Em(n.inputs,t),{inputs:[0]})},Nv=n=>{let e=n.starts,t=n.ends,r=n.axes;return sn({starts:e,ends:t,axes:r})}}),Mm,Tm,Uv,Bv,L2=Ce(()=>{bt(),Dt(),Mn(),Ot(),Mm=n=>{if(!n||n.length!==1)throw new Error("Softmax op requires 1 input.")},Tm=(n,e)=>{let t=n.dims,r=Ee.size(t),i=64,a=e.axis;if(a<0&&(a=t.length+a),a_===4?`max(max(${g}.x, ${g}.y), max(${g}.z, ${g}.w))`:_===2?`max(${g}.x, ${g}.y)`:_===3?`max(max(${g}.x, ${g}.y), ${g}.z)`:g,h=Te("x",n.dataType,n.dims,l),p=ct("result",n.dataType,n.dims,l),d=h.type.value,m=Rn(n.dataType)==="f32"?`var threadMax = ${d}(-3.402823e+38f);`:`var threadMax = ${d}(-65504.0h);`,y=g=>` var rowMaxShared : ${d}; var rowSumShared : ${d}; var threadShared : array<${d}, ${i}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${d} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${d}) { let index = row * row_stride + col; result[index] = value; } ${g.registerUniform("packedCols","i32").declareVariables(h,p)} ${g.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${i}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${m} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${d}(${c("threadShared[0]",l)}); } workgroupBarrier(); // find the rows sum var threadSum = ${d}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${d}(${zi("threadShared[0]",l)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`;return{name:"Softmax",shaderCache:{hint:`${l}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:t,dataType:n.dataType}],dispatchGroup:{x:o},programUniforms:[{type:6,data:u}]}),getShaderSource:y}},Uv=(n,e)=>{Mm(n.inputs),n.compute(Tm(n.inputs[0],e))},Bv=n=>sn({axis:n.axis})}),Am,Cm,$m,Rm,Im,Fv,Gv,z2=Ce(()=>{bt(),Dt(),Mn(),Ot(),Am=n=>{if(!n||n.length<1)throw new Error("too few inputs")},Cm=(n,e)=>{let t=[],r=e.numOutputs;return n[1].dims[0]>0&&(n[1].getBigInt64Array().forEach(i=>t.push(Number(i))),r=t.length),sn({numOutputs:r,axis:e.axis,splitSizes:t})},$m=n=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${n}u; i += 1u ) { if (index < ${Et("uniforms.size_in_split_axis","i",n)}) { return i; } } return ${n}u; }`,Rm=n=>{let e=n.length,t=[];for(let r=0;r{let t=n[0].dims,r=Ee.size(t),i=n[0].dataType,a=Ee.normalizeAxis(e.axis,t.length),s=new Array(e.numOutputs),o=Te("input",i,t.length),l=new Array(e.numOutputs),u=[],c=[],h=0,p=[{type:12,data:r}];for(let m=0;m` ${m.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)} ${$m(l.length)} ${Rm(s)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${o.offsetToIndices("global_idx")}; var index = ${o.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Et("uniforms.size_in_split_axis","output_number - 1u",l.length)}; ${o.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:e.cacheKey,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:p})}},Fv=(n,e)=>{Am(n.inputs);let t=n.inputs.length===1?e:Cm(n.inputs,e);n.compute(Im(n.inputs,t),{inputs:[0]})},Gv=n=>{let e=n.axis,t=n.splitSizes,r=n.numOutputs<0?t.length:n.numOutputs;if(r!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return sn({axis:e,numOutputs:r,splitSizes:t})}}),Qu,Pm,km,Om,Wv,N2=Ce(()=>{bt(),Dt(),Ot(),Qu=n=>Array.from(n.getBigInt64Array(),Number),Pm=n=>{if(!n||n.length!==2)throw new Error("Tile requires 2 inputs.");if(n[0].dataType!==1&&n[0].dataType!==6&&n[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(n[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(n[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Qu(n[1]).length!==n[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},km=(n,e)=>{let t=[];for(let r=0;r{let e=n[0].dims,t=Qu(n[1]),r=km(e,t),i=Ee.size(r),a=n[0].dataType,s=Te("input",a,e.length),o=ct("output",a,r.length),l=u=>` const inputShape = ${s.indices(...e)}; ${u.registerUniform("output_size","u32").declareVariables(s,o)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${o.offsetToIndices("global_idx")}; var input_indices: ${s.type.indices}; for (var i = 0; i < ${e.length}; i++) { let input_dim_i = ${s.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${o.indicesGet("output_indices","i")} % input_dim_i; ${s.indicesSet("input_indices","i","input_dim_value")} } ${o.setByOffset("global_idx",s.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...gt(n[0].dims,r)]}),getShaderSource:l}},Wv=n=>{Pm(n.inputs),n.compute(Om(n.inputs),{inputs:[0]})}}),Dm,Lm,Vv,U2=Ce(()=>{bt(),Dt(),Ot(),Dm=(n,e,t,r,i)=>{let a=ct("output_data",i,t.length,4),s=Te("a_data",e[1].dataType,e[1].dims.length,4),o=Te("b_data",e[2].dataType,e[2].dims.length,4),l=Te("c_data",e[0].dataType,e[0].dims.length,4),u,c=(h,p,d)=>`select(${p}, ${h}, ${d})`;if(!r)u=a.setByOffset("global_idx",c(s.getByOffset("global_idx"),o.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let h=(p,d,m="")=>{let y=`a_data[index_a${d}][component_a${d}]`,g=`b_data[index_b${d}][component_b${d}]`,_=`bool(c_data[index_c${d}] & (0xffu << (component_c${d} * 8)))`;return` let output_indices${d} = ${a.offsetToIndices(`global_idx * 4u + ${d}u`)}; let offset_a${d} = ${s.broadcastedIndicesToOffset(`output_indices${d}`,a)}; let offset_b${d} = ${o.broadcastedIndicesToOffset(`output_indices${d}`,a)}; let offset_c${d} = ${l.broadcastedIndicesToOffset(`output_indices${d}`,a)}; let index_a${d} = offset_a${d} / 4u; let index_b${d} = offset_b${d} / 4u; let index_c${d} = offset_c${d} / 4u; let component_a${d} = offset_a${d} % 4u; let component_b${d} = offset_b${d} % 4u; let component_c${d} = offset_c${d} % 4u; ${p}[${d}] = ${m}(${c(y,g,_)}); `};i===9?u=` var data = vec4(0); ${h("data",0,"u32")} ${h("data",1,"u32")} ${h("data",2,"u32")} ${h("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` ${h("output_data[global_idx]",0)} ${h("output_data[global_idx]",1)} ${h("output_data[global_idx]",2)} ${h("output_data[global_idx]",3)} `}return` ${n.registerUniform("vec_size","u32").declareVariables(l,s,o,a)} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${u} }`},Lm=n=>{let e=n[1].dims,t=n[2].dims,r=n[0].dims,i=n[1].dataType,a=!(Ee.areEqual(e,t)&&Ee.areEqual(t,r)),s=e,o=Ee.size(e);if(a){let u=os.calcShape(os.calcShape(e,t,!1),r,!1);if(!u)throw new Error("Can't perform where op on the given tensors");s=u,o=Ee.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>Dm(u,n,s,a,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...gt(r,e,t,s)]})}},Vv=n=>{n.compute(Lm(n.inputs))}}),Hv,B2=Ce(()=>{o2(),ey(),l2(),u2(),c2(),d2(),Q0(),Jy(),g2(),_2(),y2(),v2(),w2(),b2(),x2(),S2(),E2(),M2(),T2(),Qy(),A2(),C2(),$2(),R2(),I2(),Ad(),P2(),k2(),O2(),D2(),L2(),z2(),N2(),so(),Cd(),U2(),Hv=new Map([["Abs",[ry]],["Acos",[iy]],["Acosh",[ay]],["Add",[Ny]],["ArgMax",[Y0,Wc]],["ArgMin",[X0,Wc]],["Asin",[sy]],["Asinh",[oy]],["Atan",[ly]],["Atanh",[uy]],["Attention",[J0]],["AveragePool",[Mv,Ev]],["BatchNormalization",[ty]],["BiasAdd",[ny]],["BiasSplitGelu",[zy]],["Cast",[dy,cy]],["Ceil",[py]],["Clip",[hy]],["Concat",[K0,Z0]],["Conv",[Yc,Xc]],["ConvTranspose",[nv,tv]],["Cos",[fy]],["Cosh",[my]],["CumSum",[rv,iv]],["DepthToSpace",[av,sv]],["Div",[Uy]],["Einsum",[ov,lv]],["Elu",[gy,xl]],["Equal",[By]],["Erf",[_y]],["Exp",[yy]],["Expand",[uv]],["FastGelu",[cv]],["Floor",[vy]],["FusedConv",[Yc,Xc]],["Gather",[hv,dv]],["GatherElements",[fv,pv]],["Gelu",[wy]],["Gemm",[gv,mv]],["GlobalAveragePool",[Av,Tv]],["GlobalMaxPool",[Iv,Rv]],["Greater",[Vy]],["GreaterOrEqual",[qy]],["HardSigmoid",[Cy,Ay]],["InstanceNormalization",[_v]],["LayerNormalization",[yv]],["LeakyRelu",[by,xl]],["Less",[Hy]],["LessOrEqual",[jy]],["Log",[Ly]],["MatMul",[Zy]],["MatMulNBits",[vv,wv]],["MaxPool",[Cv,$v]],["Mul",[Fy]],["MultiHeadAttention",[xv,bv]],["Neg",[Sy]],["Not",[xy]],["Pad",[Sv]],["Pow",[Gy]],["Range",[Pv]],["Reciprocal",[Ey]],["ReduceMin",[W0]],["ReduceMean",[N0]],["ReduceMax",[G0]],["ReduceSum",[H0]],["ReduceProd",[V0]],["ReduceL1",[U0]],["ReduceL2",[B0]],["ReduceLogSum",[j0]],["ReduceLogSumExp",[F0]],["ReduceSumSquare",[q0]],["Relu",[My]],["Resize",[kv,Ov]],["RotaryEmbedding",[Dv]],["Sigmoid",[Ty]],["Sin",[$y]],["Sinh",[Ry]],["Slice",[zv,Nv]],["SkipLayerNormalization",[Lv]],["Split",[Fv,Gv]],["Sqrt",[Iy]],["Softmax",[Uv,Bv]],["Sub",[Wy]],["Tan",[Py]],["Tanh",[ky]],["ThresholdedRelu",[Dy,xl]],["Tile",[Wv]],["Transpose",[T0,A0]],["Where",[Vv]]])}),qv,F2=Ce(()=>{Ur(),wa(),Ot(),qv=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,e){this.repo.set(n,e)}run(n,e,t,r,i){Nr(n.programInfo.name);let a=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let o=[];for(let u of e)o.push({binding:o.length,resource:{buffer:u.buffer}});for(let u of t)o.push({binding:o.length,resource:{buffer:u.buffer}});i&&o.push({binding:o.length,resource:i});let l=a.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:o,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}s.setPipeline(n.computePipeline),s.setBindGroup(0,l),s.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),yr(n.programInfo.name)}dispose(){}build(n,e){Nr(n.name);let t=this.backend.device,r=[];t.features.has("shader-f16")&&r.push("enable f16;");let i=M0(e,this.backend.device.limits),a=n.getShaderSource(i),s=`${r.join(` `)} ${i.additionalImplementations} ${a}`,o=t.createShaderModule({code:s,label:n.name});mn("verbose",()=>`[WebGPU] ${n.name} shader code: ${s}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return yr(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let a=e*t*r,s=Math.ceil(Math.sqrt(a));if(s>i){if(s=Math.ceil(Math.cbrt(a)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}else return[s,s,1]}}}),zm,Nm,Um,jv,G2=Ce(()=>{Ur(),bt(),wa(),i2(),a2(),B2(),F2(),zm=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let r=0;r{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${zm(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},Um=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},jv=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t};e.features.has("chromium-experimental-timestamp-query-inside-passes")?t.push("chromium-experimental-timestamp-query-inside-passes"):e.features.has("timestamp-query")&&t.push("timestamp-query"),e.features.has("shader-f16")&&t.push("shader-f16"),this.device=await e.requestDevice(r),this.adapterInfo=new Um(await e.requestAdapterInfo()),this.gpuDataManager=S0(this),this.programManager=new qv(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,b0(n.logLevel,!!n.debug),this.device.onuncapturederror=i=>{i.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${i.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Nr(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r"u"&&(this.queryTimeBase=p);let m=Number(p-this.queryTimeBase),y=Number(d-this.queryTimeBase);if(!Number.isSafeInteger(m)||!Number.isSafeInteger(y))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:c.map(g=>({dims:g.dims,dataType:ta(g.dataType)})),outputsMetadata:h.map(g=>({dims:g.dims,dataType:ta(g.dataType)})),kernelId:a,kernelType:o,kernelName:l,programName:u,startTime:m,endTime:y});else{let g="";c.forEach((w,b)=>{g+=`input[${b}]: [${w.dims}] | ${ta(w.dataType)}, `});let _="";h.forEach((w,b)=>{_+=`output[${b}]: [${w.dims}] | ${ta(w.dataType)}, `}),console.log(`[profiling] kernel "${a}|${o}|${l}|${u}" ${g}${_}execution time: ${y-m} ns`)}js("GPU",`${u}::${p}::${d}`)}n.unmap(),this.pendingQueries.delete(n)}),yr()}run(n,e,t,r,i,a){Nr(n.name);let s=[];for(let w=0;wb):t;if(c.length!==o.length)throw new Error(`Output size ${c.length} must be equal to ${o.length}.`);let h=[],p=[];for(let w=0;w=a)throw new Error(`Invalid output index: ${c[w]}`);if(c[w]===-3)continue;let b=c[w]===-1,E=c[w]===-2,T=b||E?i(o[w].dataType,o[w].dims):r(c[w],o[w].dataType,o[w].dims);if(h.push(T),T.data===0)continue;let I=this.gpuDataManager.get(T.data);if(!I)throw new Error(`no GPU data for output: ${T.data}`);if(b&&this.temporaryData.push(I),E){let C=this.kernelPersistentData.get(this.currentKernelId);C||(C=[],this.kernelPersistentData.set(this.currentKernelId,C)),C.push(I)}p.push(I)}if(s.length!==e.length||p.length!==h.length){if(p.length===0)return yr(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let d;if(u){let w=0,b=[];u.forEach(C=>{let B=typeof C.data=="number"?[C.data]:C.data;if(B.length===0)return;let R=C.type===10?2:4,k,j;C.type===10?(j=B.length>4?16:B.length>2?8:B.length*R,k=B.length>4?16:R*B.length):(j=B.length<=2?B.length*R:16,k=16),w=Math.ceil(w/j)*j,b.push(w);let Q=C.type===10?8:4;w+=B.length>4?Math.ceil(B.length/Q)*k:B.length*R});let E=16;w=Math.ceil(w/E)*E;let T=new ArrayBuffer(w);u.forEach((C,B)=>{let R=b[B],k=typeof C.data=="number"?[C.data]:C.data;if(C.type===6)new Int32Array(T,R,k.length).set(k);else if(C.type===12)new Uint32Array(T,R,k.length).set(k);else if(C.type===10)new Uint16Array(T,R,k.length).set(k);else if(C.type===1)new Float32Array(T,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${ta(C.type)}`)});let I=this.gpuDataManager.create(w,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(I.buffer,0,T,0,w),this.gpuDataManager.release(I.id),d={offset:0,size:w,buffer:I.buffer}}let m=this.programManager.normalizeDispatchGroupSize(l),y=m[1]===1&&m[2]===1,g=Nm(n,e,y),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(n,m),this.programManager.setArtifact(g,_),mn("info",()=>`[artifact] key: ${g}, programName: ${n.name}`)),u&&_.uniformVariablesInfo){if(u.length!==_.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${u.length} in program "${_.programInfo.name}".`);for(let w=0;w`[ProgramManager] run "${n.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let w={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(w),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(w)}return this.programManager.run(_,s,p,m,d),yr(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=Hv.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let a={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,a)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,a=r.kernelName,s=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),mn("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),s(e,o[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${i}] ${a}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let a=i.get(e),s=this.gpuDataManager.registerExternalBuffer(t,r,a?.[1]);return i.set(e,[s,t]),s}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[1])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await Fc(this,n,e);return x0(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){mn("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){mn("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){mn("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),Xv={};ms(Xv,{init:()=>Yv});var Ho,Bm,Yv,W2=Ce(()=>{bt(),G2(),wa(),Dt(),Ho=class Kv{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Ee.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Ee.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Ee.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Ee.size(e)!==Ee.size(this.dims))throw new Error("Invalid new shape");return new Kv(this.module,this.dataType,this.data,e)}},Bm=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=n.HEAPU32,i=t>>>2;this.opKernelContext=r[i++];let a=r[i++];this.outputCount=r[i++],this.customDataOffset=r[i++],this.customDataSize=r[i++];let s=[];for(let o=0;otypeof s=="number"?this.inputs[s]:s)??this.inputs,r=e?.outputs??[],i=(s,o,l)=>new Ho(this.module,o,this.output(s,l),l),a=(s,o)=>{let l=Xs(s);if(!l)throw new Error(`Unsupported data type: ${s}`);let u=l*Ee.size(o),c=u>0?this.backend.gpuDataManager.create(u).id:0;return new Ho(this.module,s,c,o)};return this.backend.run(n,t,r,i,a,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let r=this.module.stackAlloc((1+e.length)*4),i=r>>2;this.module.HEAPU32[i++]=e.length;for(let a=0;a{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let a=new jv;await a.initialize(t,r),i("webgpu",[a,s=>a.alloc(s),s=>a.free(s),(s,o,l,u=!1)=>{if(u)mn("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${o}, size=${l}`),a.memcpy(s,o);else{mn("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${o}, size=${l}`);let c=e.HEAPU8.subarray(s>>>0,(s>>>0)+l);a.upload(o,c)}},async(s,o,l)=>{mn("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${o}, size=${l}`),await a.download(s,()=>e.HEAPU8.subarray(o>>>0,(o>>>0)+l))},(s,o,l)=>a.createKernel(s,o,l,e.UTF8ToString(e._JsepGetNodeName(o))),s=>a.releaseKernel(s),(s,o,l,u)=>{mn("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${s}, contextDataOffset=${o}`);let c=new Bm(e,a,o);return a.computeKernel(s,c,u)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else i("webnn")}}),Fm,Zv,Qv,xi,Gm,Zc,Jv,ew,Ju,tw,nw,rw,V2=Ce(()=>{n2(),r2(),bt(),ao(),wd(),w0(),Fm=(n,e)=>{yn()._OrtInit(n,e)!==0&&an("Can't initialize onnxruntime.")},Zv=async n=>{Fm(n.wasm.numThreads,kl(n.logLevel))},Qv=async(n,e)=>{{let t=(W2(),la(Xv)).init;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let r=n.webgpu.adapter;if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=n.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=n.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}if(!n.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await t("webgpu",yn(),n,r)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",yn(),n)}}},xi=new Map,Gm=n=>{let e=yn(),t=e.stackSave();try{let r=e.stackAlloc(8);return e._OrtGetInputOutputCount(n,r,r+4)!==0&&an("Can't get session input/output count."),[e.HEAP32[r/4],e.HEAP32[r/4+1]]}finally{e.stackRestore(t)}},Zc=n=>{let e=yn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},Jv=async(n,e)=>{let t,r,i=yn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=Zc(n);let a=0,s=0,o=0,l=[],u=[],c=[];try{if([s,l]=v0(e),e?.externalData&&i.mountExternalData){let w=[];for(let b of e.externalData){let E=typeof b=="string"?b:b.path;w.push(Ol(typeof b=="string"?b:b.data).then(T=>{i.mountExternalData(E,T)}))}await Promise.all(w)}a=await i._OrtCreateSession(t,r,s),a===0&&an("Can't create a session.");let[h,p]=Gm(a),d=!!e?.enableGraphCapture,m=[],y=[],g=[];for(let w=0;ww==="gpu-buffer")&&(o=i._OrtCreateBinding(a),o===0&&an("Can't create IO binding."),_={handle:o,outputPreferredLocations:g,outputPreferredLocationsEncoded:g.map(w=>Bc(w))}),xi.set(a,[a,u,c,_,d,!1]),[a,m,y]}catch(h){throw u.forEach(p=>i._OrtFree(p)),c.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o),a!==0&&i._OrtReleaseSession(a),h}finally{i._free(t),s!==0&&i._OrtReleaseSessionOptions(s),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},ew=n=>{let e=yn(),t=xi.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,a,s,o]=t;s&&(o&&e._OrtClearBoundOutputs(s.handle),e._OrtReleaseBinding(s.handle)),e.jsepOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),a.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r),xi.delete(n)},Ju=(n,e,t,r,i,a=!1)=>{if(!n){e.push(0);return}let s=yn(),o=n[0],l=n[1],u=n[3],c,h;if(o==="string"&&u==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a&&u!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(u==="gpu-buffer"){let m=n[2].gpuBuffer,y=Xs(Uc(o));h=l.reduce((_,w)=>_*w,1)*y;let g=s.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');c=g(r,i,m,h)}else{let m=n[2];if(Array.isArray(m)){h=4*m.length,c=s._malloc(h),t.push(c);let y=c/4;for(let g=0;gs.HEAP32[m++]=g);let y=s._OrtCreateTensor(Uc(o),c,h,d,l.length,Bc(u));y===0&&an(`Can't create tensor for input/output. session=${r}, index=${i}.`),e.push(y)}finally{s.stackRestore(p)}},tw=async(n,e,t,r,i,a)=>{let s=yn(),o=xi.get(n);if(!o)throw new Error(`cannot run inference. invalid session id: ${n}`);let l=o[0],u=o[1],c=o[2],h=o[3],p=o[4],d=o[5],m=e.length,y=r.length,g=0,_=[],w=[],b=[],E=[],T=s.stackSave(),I=s.stackAlloc(m*4),C=s.stackAlloc(m*4),B=s.stackAlloc(y*4),R=s.stackAlloc(y*4);try{[g,_]=y0(a);for(let L=0;LDe*Xe,1);W=ta(de);let et=h?.outputPreferredLocations[r[L]];if(W==="string"){if(et==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let De=[],Xe=ae/4;for(let te=0;te0){let De=s.jsepGetBuffer;if(!De)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Xe=De(ae),te=Xs(de);if(te===void 0||!xd(W))throw new Error(`Unsupported data type: ${W}`);J=!0,$.push([W,ke,{gpuBuffer:Xe,download:s.jsepCreateDownloader(Xe,Be*te,W),dispose:()=>{s._OrtReleaseTensor(H)}},"gpu-buffer"])}else{let De=bd(W),Xe=new De(Be);new Uint8Array(Xe.buffer,Xe.byteOffset,Xe.byteLength).set(s.HEAPU8.subarray(ae,ae+Xe.byteLength)),$.push([W,ke,Xe,"cpu"])}}finally{s.stackRestore(K),W==="string"&&ae&&s._free(ae),J||s._OrtReleaseTensor(H)}}return h&&!p&&(s._OrtClearBoundOutputs(h.handle),xi.set(n,[l,u,c,h,p,!1])),$}finally{s.stackRestore(T),w.forEach(k=>s._OrtReleaseTensor(k)),b.forEach(k=>s._OrtReleaseTensor(k)),E.forEach(k=>s._free(k)),g!==0&&s._OrtReleaseRunOptions(g),_.forEach(k=>s._free(k))}},nw=n=>{let e=yn(),t=xi.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&an("Can't get an profile file name."),e._OrtFree(i)},rw=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),H2=fs((n,e)=>{e.exports='/*!\n * ONNX Runtime Web v1.18.0\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var ao=Object.defineProperty;var nl=Object.getOwnPropertyDescriptor;var ol=Object.getOwnPropertyNames;var il=Object.prototype.hasOwnProperty;var Y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gn=(e,t)=>{for(var r in t)ao(e,r,{get:t[r],enumerable:!0})},al=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ol(t))!il.call(e,i)&&i!==r&&ao(e,i,{get:()=>t[i],enumerable:!(o=nl(t,i))||o.enumerable});return e};var wr=e=>al(ao({},"__esModule",{value:!0}),e);var so={};gn(so,{createReadStream:()=>Ai,readFile:()=>sl,readFileSync:()=>ul});var sl,ul,Ai,uo=Y(()=>{sl=void 0,ul=void 0,Ai=void 0});var lo={};gn(lo,{join:()=>dl});var dl,co=Y(()=>{dl=void 0});var Ei=Wr((Ti,po)=>{"use strict";var Ii=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(t={}){var r=t,o,i,u=new Promise((s,m)=>{o=s,i=m});r.mountExternalData=(s,m)=>{(r.eb||(r.eb=new Map)).set(s,m)},r.unmountExternalData=()=>{delete r.eb};let a=()=>{let s=(g,$,T)=>(...B)=>{let H=dt,q=$?.();B=g(...B);let te=$?.();return q!==te&&(g=te,T(q),$=T=null),dt!=H?tn():B},m=g=>async(...$)=>{try{if(r.cb)throw Error("Session already started");let T=r.cb={xb:$[0],errors:[]},B=await g(...$);if(r.cb!==T)throw Error("Session mismatch");r.kb?.flush();let H=T.errors;if(0te),0r._OrtCreateSession,g=>r._OrtCreateSession=g),r._OrtRun=m(s(r._OrtRun,()=>r._OrtRun,g=>r._OrtRun=g)),r._OrtRunWithBinding=m(s(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,g=>r._OrtRunWithBinding=g)),r._OrtBindInput=s(r._OrtBindInput,()=>r._OrtBindInput,g=>r._OrtBindInput=g),a=void 0};r.jsepInit=(s,m)=>{if(a?.(),s==="webgpu"){[r.kb,r.pb,r.tb,r.lb,r.sb,r.Ra,r.ub,r.wb,r.qb,r.rb,r.vb]=m;let g=r.kb;r.jsepRegisterBuffer=($,T,B,H)=>g.registerBuffer($,T,B,H),r.jsepGetBuffer=$=>g.getBuffer($),r.jsepCreateDownloader=($,T,B)=>g.createDownloader($,T,B),r.jsepOnReleaseSession=$=>{g.onReleaseSession($)},r.jsepOnRunStart=$=>g.onRunStart($)}};var c=Object.assign({},r),p="./this.program",h=(s,m)=>{throw m},d=typeof window=="object",y=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_="",v,S,A;if(w){var I=(uo(),wr(so)),x=(co(),wr(lo));_=y?x.dirname(_)+"/":__dirname+"/",v=(s,m)=>(s=Ke(s)?new URL(s):x.normalize(s),I.readFileSync(s,m?void 0:"utf8")),A=s=>(s=v(s,!0),s.buffer||(s=new Uint8Array(s)),s),S=(s,m,g,$=!0)=>{s=Ke(s)?new URL(s):x.normalize(s),I.readFile(s,$?void 0:"utf8",(T,B)=>{T?g(T):m($?B.buffer:B)})},!r.thisProgram&&1{throw process.exitCode=s,m}}else(d||y)&&(y?_=self.location.href:typeof document<"u"&&document.currentScript&&(_=document.currentScript.src),e&&(_=e),_.startsWith("blob:")?_="":_=_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1),v=s=>{var m=new XMLHttpRequest;return m.open("GET",s,!1),m.send(null),m.responseText},y&&(A=s=>{var m=new XMLHttpRequest;return m.open("GET",s,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),S=(s,m,g)=>{var $=new XMLHttpRequest;$.open("GET",s,!0),$.responseType="arraybuffer",$.onload=()=>{$.status==200||$.status==0&&$.response?m($.response):g()},$.onerror=g,$.send(null)});var E=console.log.bind(console),P=console.error.bind(console);Object.assign(r,c),c=null;var O,R=!1,L,N,K,Q,he,W,se,Ce,We,ee,ae;function Ae(){var s=O.buffer;r.HEAP8=N=new Int8Array(s),r.HEAP16=Q=new Int16Array(s),r.HEAPU8=K=new Uint8Array(s),r.HEAPU16=he=new Uint16Array(s),r.HEAP32=W=new Int32Array(s),r.HEAPU32=se=new Uint32Array(s),r.HEAPF32=Ce=new Float32Array(s),r.HEAPF64=ae=new Float64Array(s),r.HEAP64=We=new BigInt64Array(s),r.HEAPU64=ee=new BigUint64Array(s)}var me=[],ie=[],ue=[],le=0,qe=null,G=null;function ne(s){throw s="Aborted("+s+")",P(s),R=!0,L=1,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),i(s),s}var xe=s=>s.startsWith("data:application/octet-stream;base64,"),Ke=s=>s.startsWith("file://"),Be;if(Be="ort-wasm-simd.wasm",!xe(Be)){var Ge=Be;Be=r.locateFile?r.locateFile(Ge,_):_+Ge}function Ut(s){if(A)return A(s);throw"both async and sync fetching of the wasm failed"}function Ne(s){if(d||y){if(typeof fetch=="function"&&!Ke(s))return fetch(s,{credentials:"same-origin"}).then(m=>{if(!m.ok)throw`failed to load wasm binary file at \'${s}\'`;return m.arrayBuffer()}).catch(()=>Ut(s));if(S)return new Promise((m,g)=>{S(s,$=>m(new Uint8Array($)),g)})}return Promise.resolve().then(()=>Ut(s))}function Ye(s,m,g){return Ne(s).then($=>WebAssembly.instantiate($,m)).then(g,$=>{P(`failed to asynchronously prepare wasm: ${$}`),ne($)})}function mt(s,m){var g=Be;return typeof WebAssembly.instantiateStreaming!="function"||xe(g)||Ke(g)||w||typeof fetch!="function"?Ye(g,s,m):fetch(g,{credentials:"same-origin"}).then($=>WebAssembly.instantiateStreaming($,s).then(m,function(T){return P(`wasm streaming compile failed: ${T}`),P("falling back to ArrayBuffer instantiation"),Ye(g,s,m)}))}var Rt={824920:(s,m,g,$)=>{if(typeof r>"u"||!r.eb)return 1;if(s=je(s>>>0),s.startsWith("./")&&(s=s.substring(2)),s=r.eb.get(s),!s)return 2;if(m>>>=0,g>>>=0,m+g>s.byteLength)return 3;try{return K.set(s.subarray(m,m+g),$>>>0>>>0),0}catch{return 4}},825421:()=>{r.qb()},825452:()=>{r.rb()},825481:()=>{r.vb()},825506:s=>r.pb(s),825539:s=>r.tb(s),825571:(s,m,g)=>{r.lb(s,m,g,!0)},825610:(s,m,g)=>{r.lb(s,m,g)},825643:s=>{r.Ra("Abs",s,void 0)},825694:s=>{r.Ra("Neg",s,void 0)},825745:s=>{r.Ra("Floor",s,void 0)},825798:s=>{r.Ra("Ceil",s,void 0)},825850:s=>{r.Ra("Reciprocal",s,void 0)},825908:s=>{r.Ra("Sqrt",s,void 0)},825960:s=>{r.Ra("Exp",s,void 0)},826011:s=>{r.Ra("Erf",s,void 0)},826062:s=>{r.Ra("Sigmoid",s,void 0)},826117:(s,m,g)=>{r.Ra("HardSigmoid",s,{alpha:m,beta:g})},826196:s=>{r.Ra("Log",s,void 0)},826247:s=>{r.Ra("Sin",s,void 0)},826298:s=>{r.Ra("Cos",s,void 0)},826349:s=>{r.Ra("Tan",s,void 0)},826400:s=>{r.Ra("Asin",s,void 0)},826452:s=>{r.Ra("Acos",s,void 0)},826504:s=>{r.Ra("Atan",s,void 0)},826556:s=>{r.Ra("Sinh",s,void 0)},826608:s=>{r.Ra("Cosh",s,void 0)},826660:s=>{r.Ra("Asinh",s,void 0)},826713:s=>{r.Ra("Acosh",s,void 0)},826766:s=>{r.Ra("Atanh",s,void 0)},826819:s=>{r.Ra("Tanh",s,void 0)},826871:s=>{r.Ra("Not",s,void 0)},826922:(s,m,g)=>{r.Ra("Clip",s,{min:m,max:g})},826991:s=>{r.Ra("Clip",s,void 0)},827043:(s,m)=>{r.Ra("Elu",s,{alpha:m})},827101:s=>{r.Ra("Relu",s,void 0)},827153:(s,m)=>{r.Ra("LeakyRelu",s,{alpha:m})},827217:(s,m)=>{r.Ra("ThresholdedRelu",s,{alpha:m})},827287:(s,m)=>{r.Ra("Cast",s,{to:m})},827345:s=>{r.Ra("Add",s,void 0)},827396:s=>{r.Ra("Sub",s,void 0)},827447:s=>{r.Ra("Mul",s,void 0)},827498:s=>{r.Ra("Div",s,void 0)},827549:s=>{r.Ra("Pow",s,void 0)},827600:s=>{r.Ra("Equal",s,void 0)},827653:s=>{r.Ra("Greater",s,void 0)},827708:s=>{r.Ra("GreaterOrEqual",s,void 0)},827770:s=>{r.Ra("Less",s,void 0)},827822:s=>{r.Ra("LessOrEqual",s,void 0)},827881:(s,m,g,$,T)=>{r.Ra("ReduceMean",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828040:(s,m,g,$,T)=>{r.Ra("ReduceMax",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828198:(s,m,g,$,T)=>{r.Ra("ReduceMin",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828356:(s,m,g,$,T)=>{r.Ra("ReduceProd",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828515:(s,m,g,$,T)=>{r.Ra("ReduceSum",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828673:(s,m,g,$,T)=>{r.Ra("ReduceL1",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828830:(s,m,g,$,T)=>{r.Ra("ReduceL2",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828987:(s,m,g,$,T)=>{r.Ra("ReduceLogSum",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829148:(s,m,g,$,T)=>{r.Ra("ReduceSumSquare",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829312:(s,m,g,$,T)=>{r.Ra("ReduceLogSumExp",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829476:s=>{r.Ra("Where",s,void 0)},829529:(s,m,g)=>{r.Ra("Transpose",s,{perm:m?Array.from(W.subarray(m>>>0,g>>>0)):[]})},829637:(s,m,g,$)=>{r.Ra("DepthToSpace",s,{blocksize:m,mode:je(g),format:$?"NHWC":"NCHW"})},829770:(s,m,g,$)=>{r.Ra("DepthToSpace",s,{blocksize:m,mode:je(g),format:$?"NHWC":"NCHW"})},829903:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be)=>{r.Ra("ConvTranspose",s,{format:te?"NHWC":"NCHW",autoPad:m,dilations:[g],group:$,kernelShape:[T],pads:[B,H],strides:[q],wIsConst:()=>!!N[X>>>0],outputPadding:de?Array.from(W.subarray(de>>>0,Ee>>>0)):[],outputShape:Oe?Array.from(W.subarray(Oe>>>0,D>>>0)):[],activation:je(be)})},830304:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D)=>{r.Ra("ConvTranspose",s,{format:q?"NHWC":"NCHW",autoPad:m,dilations:Array.from(W.subarray(g>>>0,(g>>>0)+2>>>0)),group:$,kernelShape:Array.from(W.subarray(T>>>0,(T>>>0)+2>>>0)),pads:Array.from(W.subarray(B>>>0,(B>>>0)+4>>>0)),strides:Array.from(W.subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!N[te>>>0],outputPadding:X?Array.from(W.subarray(X>>>0,de>>>0)):[],outputShape:Ee?Array.from(W.subarray(Ee>>>0,Oe>>>0)):[],activation:je(D)})},830869:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be)=>{r.Ra("ConvTranspose",s,{format:te?"NHWC":"NCHW",autoPad:m,dilations:[g],group:$,kernelShape:[T],pads:[B,H],strides:[q],wIsConst:()=>!!N[X>>>0],outputPadding:de?Array.from(W.subarray(de>>>0,Ee>>>0)):[],outputShape:Oe?Array.from(W.subarray(Oe>>>0,D>>>0)):[],activation:je(be)})},831270:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D)=>{r.Ra("ConvTranspose",s,{format:q?"NHWC":"NCHW",autoPad:m,dilations:Array.from(W.subarray(g>>>0,(g>>>0)+2>>>0)),group:$,kernelShape:Array.from(W.subarray(T>>>0,(T>>>0)+2>>>0)),pads:Array.from(W.subarray(B>>>0,(B>>>0)+4>>>0)),strides:Array.from(W.subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!N[te>>>0],outputPadding:X?Array.from(W.subarray(X>>>0,de>>>0)):[],outputShape:Ee?Array.from(W.subarray(Ee>>>0,Oe>>>0)):[],activation:je(D)})},831835:(s,m)=>{r.Ra("GlobalAveragePool",s,{format:m?"NHWC":"NCHW"})},831926:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("AveragePool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832210:(s,m)=>{r.Ra("GlobalAveragePool",s,{format:m?"NHWC":"NCHW"})},832301:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("AveragePool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832585:(s,m)=>{r.Ra("GlobalMaxPool",s,{format:m?"NHWC":"NCHW"})},832672:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("MaxPool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832952:(s,m)=>{r.Ra("GlobalMaxPool",s,{format:m?"NHWC":"NCHW"})},833039:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("MaxPool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},833319:(s,m,g,$,T)=>{r.Ra("Gemm",s,{alpha:m,beta:g,transA:$,transB:T})},833423:s=>{r.Ra("MatMul",s,void 0)},833477:(s,m,g,$)=>{r.Ra("ArgMax",s,{keepDims:!!m,selectLastIndex:!!g,axis:$})},833585:(s,m,g,$)=>{r.Ra("ArgMin",s,{keepDims:!!m,selectLastIndex:!!g,axis:$})},833693:(s,m)=>{r.Ra("Softmax",s,{axis:m})},833756:(s,m)=>{r.Ra("Concat",s,{axis:m})},833816:(s,m,g,$,T)=>{r.Ra("Split",s,{axis:m,numOutputs:g,splitSizes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},833956:s=>{r.Ra("Expand",s,void 0)},834010:(s,m)=>{r.Ra("Gather",s,{axis:Number(m)})},834081:(s,m)=>{r.Ra("GatherElements",s,{axis:Number(m)})},834160:(s,m,g,$,T,B,H,q,te,X,de)=>{r.Ra("Resize",s,{antialias:m,axes:g?Array.from(W.subarray(g>>>0,$>>>0)):[],coordinateTransformMode:je(T),cubicCoeffA:B,excludeOutside:H,extrapolationValue:q,keepAspectRatioPolicy:je(te),mode:je(X),nearestMode:je(de)})},834506:(s,m,g,$,T,B,H)=>{r.Ra("Slice",s,{starts:m?Array.from(W.subarray(m>>>0,g>>>0)):[],ends:$?Array.from(W.subarray($>>>0,T>>>0)):[],axes:B?Array.from(W.subarray(B>>>0,H>>>0)):[]})},834722:s=>{r.Ra("Tile",s,void 0)},834774:(s,m,g,$)=>{r.Ra("LayerNormalization",s,{axis:m,epsilon:g,simplified:!!$})},834885:(s,m,g)=>{r.Ra("InstanceNormalization",s,{epsilon:m,format:g?"NHWC":"NCHW"})},834999:(s,m,g)=>{r.Ra("InstanceNormalization",s,{epsilon:m,format:g?"NHWC":"NCHW"})},835113:s=>{r.Ra("Range",s,void 0)},835166:(s,m)=>{r.Ra("Einsum",s,{equation:je(m)})},835247:(s,m,g,$,T)=>{r.Ra("Pad",s,{mode:m,value:g,pads:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},835374:(s,m,g,$,T,B)=>{r.Ra("BatchNormalization",s,{epsilon:m,momentum:g,spatial:!!T,trainingMode:!!$,format:B?"NHWC":"NCHW"})},835543:(s,m,g,$,T,B)=>{r.Ra("BatchNormalization",s,{epsilon:m,momentum:g,spatial:!!T,trainingMode:!!$,format:B?"NHWC":"NCHW"})},835712:(s,m,g)=>{r.Ra("CumSum",s,{exclusive:Number(m),reverse:Number(g)})},835809:(s,m,g,$,T,B,H,q,te)=>{r.Ra("Attention",s,{numHeads:m,isUnidirectional:g,maskFilterValue:$,scale:T,doRotary:B,qkvHiddenSizes:H?Array.from(W.subarray(Number(q)>>>0,Number(q)+H>>>0)):[],pastPresentShareBuffer:!!te})},836081:s=>{r.Ra("BiasAdd",s,void 0)},836136:s=>{r.Ra("BiasSplitGelu",s,void 0)},836197:s=>{r.Ra("FastGelu",s,void 0)},836253:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe)=>{r.Ra("Conv",s,{format:te?"NHWC":"NCHW",auto_pad:m,dilations:[g],group:$,kernel_shape:[T],pads:B?Array.from(W.subarray(B>>>0,H>>>0)):[],strides:[q],w_is_const:()=>!!N[X>>>0],activation:je(de),activation_params:Ee?Array.from(Ce.subarray(Ee>>>0,Oe>>>0)):[]})},836623:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("Conv",s,{format:Ee?"NHWC":"NCHW",auto_pad:m,dilations:[g,$],group:T,kernel_shape:[B,H],pads:q?Array.from(W.subarray(q>>>0,te>>>0)):[],strides:[X,de],w_is_const:()=>!!N[Oe>>>0],activation:je(D),activation_params:be?Array.from(Ce.subarray(be>>>0,Ie>>>0)):[]})},837014:s=>{r.Ra("Gelu",s,void 0)},837066:(s,m,g,$,T,B)=>{r.Ra("MatMulNBits",s,{k:m,n:g,accuracyLevel:$,bits:T,blockSize:B})},837193:(s,m,g,$,T,B)=>{r.Ra("MultiHeadAttention",s,{numHeads:m,isUnidirectional:g,maskFilterValue:$,scale:T,doRotary:B})},837352:(s,m,g,$,T)=>{r.Ra("RotaryEmbedding",s,{interleaved:!!m,numHeads:g,rotaryEmbeddingDim:$,scale:T})},837491:(s,m,g)=>{r.Ra("SkipLayerNormalization",s,{epsilon:m,simplified:!!g})},837593:(s,m,g)=>{r.Ra("SkipLayerNormalization",s,{epsilon:m,simplified:!!g})},837695:(s,m,g,$)=>{r.Ra("LayerNormalization",s,{axis:m,epsilon:g,simplified:!!$})},837806:s=>{r.ub(s)},837840:(s,m)=>r.wb(s,m,r.cb.xb,r.cb.errors)};function qt(s){this.name="ExitStatus",this.message=`Program terminated with exit(${s})`,this.status=s}class Vt{constructor(m){this.hb=m-24}}var sr=0,jt=0,xr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Kt=(s,m,g)=>{m>>>=0;var $=m+g;for(g=m;s[g]&&!(g>=$);)++g;if(16T?$+=String.fromCharCode(T):(T-=65536,$+=String.fromCharCode(55296|T>>10,56320|T&1023))}}else $+=String.fromCharCode(T)}return $},je=(s,m)=>(s>>>=0)?Kt(K,s,m):"",Wt=s=>{for(var m=0,g=0;g=$?m++:2047>=$?m+=2:55296<=$&&57343>=$?(m+=4,++g):m+=3}return m},at=(s,m,g,$)=>{if(g>>>=0,!(0<$))return 0;var T=g;$=g+$-1;for(var B=0;B=H){var q=s.charCodeAt(++B);H=65536+((H&1023)<<10)|q&1023}if(127>=H){if(g>=$)break;m[g++>>>0]=H}else{if(2047>=H){if(g+1>=$)break;m[g++>>>0]=192|H>>6}else{if(65535>=H){if(g+2>=$)break;m[g++>>>0]=224|H>>12}else{if(g+3>=$)break;m[g++>>>0]=240|H>>18,m[g++>>>0]=128|H>>12&63}m[g++>>>0]=128|H>>6&63}m[g++>>>0]=128|H&63}}return m[g>>>0]=0,g-T},Cr,ft=s=>{for(var m="";K[s>>>0];)m+=Cr[K[s++>>>0]];return m},ur={},Ar={},Ir={},st;function Tr(s,m,g={}){var $=m.name;if(!s)throw new st(`type "${$}" must have a positive integer typeid pointer`);if(Ar.hasOwnProperty(s)){if(g.nb)return;throw new st(`Cannot register type \'${$}\' twice`)}Ar[s]=m,delete Ir[s],ur.hasOwnProperty(s)&&(m=ur[s],delete ur[s],m.forEach(T=>T()))}function ht(s,m,g={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Tr(s,m,g)}var bt=(s,m,g)=>{switch(m){case 1:return g?$=>N[$>>>0]:$=>K[$>>>0];case 2:return g?$=>Q[$>>>1>>>0]:$=>he[$>>>1>>>0];case 4:return g?$=>W[$>>>2>>>0]:$=>se[$>>>2>>>0];case 8:return g?$=>We[$>>>3]:$=>ee[$>>>3];default:throw new TypeError(`invalid integer width (${m}): ${s}`)}},Er=[],Te=[];function dr(s){s>>>=0,9{if(!s)throw new st("Cannot use deleted val. handle = "+s);return Te[s]},ut=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Er.pop()||Te.length;return Te[m]=s,Te[m+1]=1,m}};function lr(s){return this.fromWireType(se[s>>>2>>>0])}var Fn={name:"emscripten::val",fromWireType:s=>{var m=Xe(s);return dr(s),m},toWireType:(s,m)=>ut(m),argPackAdvance:8,readValueFromPointer:lr,bb:null},ge=(s,m)=>{switch(m){case 4:return function(g){return this.fromWireType(Ce[g>>>2>>>0])};case 8:return function(g){return this.fromWireType(ae[g>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${s}`)}},Yt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,jr=(s,m)=>{for(var g=s>>1,$=g+m/2;!(g>=$)&&he[g>>>0];)++g;if(g<<=1,32>>0,g>>>0));for(g="",$=0;!($>=m/2);++$){var T=Q[s+2*$>>>1>>>0];if(T==0)break;g+=String.fromCharCode(T)}return g},qn=(s,m,g)=>{if(g??=2147483647,2>g)return 0;g-=2;var $=m;g=g<2*s.length?g/2:s.length;for(var T=0;T>>1>>>0]=s.charCodeAt(T),m+=2;return Q[m>>>1>>>0]=0,m-$},Kr=s=>2*s.length,jn=(s,m)=>{for(var g=0,$="";!(g>=m/4);){var T=W[s+4*g>>>2>>>0];if(T==0)break;++g,65536<=T?(T-=65536,$+=String.fromCharCode(55296|T>>10,56320|T&1023)):$+=String.fromCharCode(T)}return $},Yr=(s,m,g)=>{if(m>>>=0,g??=2147483647,4>g)return 0;var $=m;g=$+g-4;for(var T=0;T=B){var H=s.charCodeAt(++T);B=65536+((B&1023)<<10)|H&1023}if(W[m>>>2>>>0]=B,m+=4,m+4>g)break}return W[m>>>2>>>0]=0,m-$},Zr=s=>{for(var m=0,g=0;g=$&&++g,m+=4}return m},cr=(s,m)=>{var g=Ar[s];if(g===void 0)throw s=Mr(s),g=ft(s),rt(s),new st(`${m} has unknown type ${g}`);return g},Pr=(s,m,g)=>{var $=[];return s=s.toWireType($,g),$.length&&(se[m>>>2>>>0]=ut($)),s},He=s=>{try{s()}catch(m){ne(m)}},Xr=s=>{if(!R)try{s();try{L=L=s=L,r.onExit?.(s),R=!0,h(s,new qt(s))}catch(m){m instanceof qt||m=="unwind"||h(1,m)}}catch(m){m instanceof qt||m=="unwind"||h(1,m)}};function Qr(){var s=pe,m={};for(let[g,$]of Object.entries(s))m[g]=typeof $=="function"?(...T)=>{Zt.push(g);try{return $(...T)}finally{R||(Zt.pop(),dt&>===1&&Zt.length===0&&(gt=0,He(dn),typeof Fibers<"u"&&Fibers.Db()))}}:$;return m}var gt=0,dt=null,Bt=0,Zt=[],kr={},Or={},Jr=0,pr=null,en=[];function tn(){return new Promise((s,m)=>{pr={resolve:s,reject:m}})}function rn(){var s=Nt(65548),m=s+12;se[s>>>2>>>0]=m,se[s+4>>>2>>>0]=m+65536,m=Zt[0];var g=kr[m];return g===void 0&&(g=Jr++,kr[m]=g,Or[g]=m),W[s+8>>>2>>>0]=g,s}function nn(s){if(!R){if(gt===0){var m=!1,g=!1;s(($=0)=>{if(!R&&(Bt=$,m=!0,g)){gt=2,He(()=>vt(dt)),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.resume(),$=!1;try{var T=(0,pe[Or[W[dt+8>>>2>>>0]]])()}catch(q){T=q,$=!0}var B=!1;if(!dt){var H=pr;H&&(pr=null,($?H.reject:H.resolve)(T),B=!0)}if($&&!B)throw T}}),g=!0,m||(gt=1,dt=rn(),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.pause(),He(()=>Jt(dt)))}else gt===2?(gt=0,He(ct),rt(dt),dt=null,en.forEach(Xr)):ne(`invalid state: ${gt}`);return Bt}}function Rr(s){return nn(m=>{s().then(m)})}var Xt=[],on={},nt=s=>{var m=on[s];return m===void 0?ft(s):m},mr=()=>typeof globalThis=="object"?globalThis:Function("return this")(),Br=s=>{var m=Xt.length;return Xt.push(s),m},Kn=(s,m)=>{for(var g=Array(s),$=0;$>>2>>>0],"parameter "+$);return g},wt=(s,m)=>Object.defineProperty(m,"name",{value:s});function Yn(s){var m=Function;if(!(m instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof m} which is not a function`);var g=wt(m.name||"unknownFunctionName",function(){});return g.prototype=m.prototype,g=new g,s=m.apply(g,s),s instanceof Object?s:g}var Je=s=>s%4===0&&(s%100!==0||s%400===0),Dr=[0,31,60,91,121,152,182,213,244,274,305,335],fr=[0,31,59,90,120,151,181,212,243,273,304,334],lt=[],hr=(s,m)=>{lt.length=0;for(var g;g=K[s++>>>0];){var $=g!=105;$&=g!=112,m+=$&&m%8?4:0,lt.push(g==112?se[m>>>2>>>0]:g==106?We[m>>>3]:g==105?W[m>>>2>>>0]:ae[m>>>3>>>0]),m+=$?8:4}return lt},Qe={},ot=()=>{if(!Qt){var s={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"},m;for(m in Qe)Qe[m]===void 0?delete s[m]:s[m]=Qe[m];var g=[];for(m in s)g.push(`${m}=${s[m]}`);Qt=g}return Qt},Qt,Zn=[null,[],[]],an=[31,29,31,30,31,30,31,31,30,31,30,31],zr=[31,28,31,30,31,30,31,31,30,31,30,31];function Xn(s){var m=Array(Wt(s)+1);return at(s,m,0,m.length),m}function sn(s,m,g,$){function T(D,be,Ie){for(D=typeof D=="number"?D.toString():D||"";D.lengthMt?-1:0zt-D.getDate())be-=zt-D.getDate()+1,D.setDate(1),11>Ie?D.setMonth(Ie+1):(D.setMonth(0),D.setFullYear(D.getFullYear()+1));else{D.setDate(D.getDate()+be);break}}return Ie=new Date(D.getFullYear()+1,0,4),be=q(new Date(D.getFullYear(),0,4)),Ie=q(Ie),0>=H(be,D)?0>=H(Ie,D)?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}s>>>=0,m>>>=0,g>>>=0,$>>>=0;var X=se[$+40>>>2>>>0];$={Ab:W[$>>>2>>>0],zb:W[$+4>>>2>>>0],fb:W[$+8>>>2>>>0],jb:W[$+12>>>2>>>0],gb:W[$+16>>>2>>>0],ab:W[$+20>>>2>>>0],Va:W[$+24>>>2>>>0],$a:W[$+28>>>2>>>0],Cb:W[$+32>>>2>>>0],yb:W[$+36>>>2>>>0],Bb:X?je(X):""},g=je(g),X={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var de in X)g=g.replace(new RegExp(de,"g"),X[de]);var Ee="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Oe="January February March April May June July August September October November December".split(" ");X={"%a":D=>Ee[D.Va].substring(0,3),"%A":D=>Ee[D.Va],"%b":D=>Oe[D.gb].substring(0,3),"%B":D=>Oe[D.gb],"%C":D=>B((D.ab+1900)/100|0,2),"%d":D=>B(D.jb,2),"%e":D=>T(D.jb,2," "),"%g":D=>te(D).toString().substring(2),"%G":te,"%H":D=>B(D.fb,2),"%I":D=>(D=D.fb,D==0?D=12:12{for(var be=0,Ie=0;Ie<=D.gb-1;be+=(Je(D.ab+1900)?an:zr)[Ie++]);return B(D.jb+be,3)},"%m":D=>B(D.gb+1,2),"%M":D=>B(D.zb,2),"%n":()=>`\n`,"%p":D=>0<=D.fb&&12>D.fb?"AM":"PM","%S":D=>B(D.Ab,2),"%t":()=>" ","%u":D=>D.Va||7,"%U":D=>B(Math.floor((D.$a+7-D.Va)/7),2),"%V":D=>{var be=Math.floor((D.$a+7-(D.Va+6)%7)/7);if(2>=(D.Va+371-D.$a-2)%7&&be++,be)be==53&&(Ie=(D.Va+371-D.$a)%7,Ie==4||Ie==3&&Je(D.ab)||(be=1));else{be=52;var Ie=(D.Va+7-D.$a-1)%7;(Ie==4||Ie==5&&Je(D.ab%400-1))&&be++}return B(be,2)},"%w":D=>D.Va,"%W":D=>B(Math.floor((D.$a+7-(D.Va+6)%7)/7),2),"%y":D=>(D.ab+1900).toString().substring(2),"%Y":D=>D.ab+1900,"%z":D=>{D=D.yb;var be=0<=D;return D=Math.abs(D)/60,(be?"+":"-")+("0000"+(D/60*100+D%60)).slice(-4)},"%Z":D=>D.Bb,"%%":()=>"%"},g=g.replace(/%%/g,"\\0\\0");for(de in X)g.includes(de)&&(g=g.replace(new RegExp(de,"g"),X[de]($)));return g=g.replace(/\\0\\0/g,"%"),de=Xn(g),de.length>m?0:(N.set(de,s>>>0),de.length-1)}for(var un=Array(256),gr=0;256>gr;++gr)un[gr]=String.fromCharCode(gr);Cr=un,st=r.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},r.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},Te.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>Te.length/2-5-Er.length;var Qn={ia:function(s,m,g){return Rr(async()=>{await r.sb(s,m,g)})},a:function(s,m,g){s>>>=0;var $=new Vt(s);throw se[$.hb+16>>>2>>>0]=0,se[$.hb+4>>>2>>>0]=m>>>0,se[$.hb+8>>>2>>>0]=g>>>0,sr=s,jt++,sr},y:function(){return 0},ea:function(){},R:function(){},T:function(){},ga:function(){return 0},ca:function(){},Z:function(){},ba:function(){},G:function(){},S:function(){},P:function(){},da:function(){},Q:function(){},C:function(s,m,g){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:$=>$,toWireType:function($,T){if(typeof T!="bigint"&&typeof T!="number")throw T===null?T="null":($=typeof T,T=$==="object"||$==="array"||$==="function"?T.toString():""+T),new TypeError(`Cannot convert "${T}" to ${this.name}`);return typeof T=="number"&&(T=BigInt(T)),T},argPackAdvance:8,readValueFromPointer:bt(m,g>>>0,m.indexOf("u")==-1),bb:null})},K:function(s,m,g,$){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:function(T){return!!T},toWireType:function(T,B){return B?g:$},argPackAdvance:8,readValueFromPointer:function(T){return this.fromWireType(K[T>>>0])},bb:null})},J:function(s){return ht(s>>>0,Fn)},B:function(s,m,g){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:$=>$,toWireType:($,T)=>T,argPackAdvance:8,readValueFromPointer:ge(m,g>>>0),bb:null})},s:function(s,m,g,$,T){if(s>>>=0,g>>>=0,m=ft(m>>>0),T===-1&&(T=4294967295),T=q=>q,$===0){var B=32-8*g;T=q=>q<>>B}var H=m.includes("unsigned")?function(q,te){return te>>>0}:function(q,te){return te};ht(s,{name:m,fromWireType:T,toWireType:H,argPackAdvance:8,readValueFromPointer:bt(m,g,$!==0),bb:null})},o:function(s,m,g){function $(B){return new T(N.buffer,se[B+4>>>2>>>0],se[B>>>2>>>0])}var T=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];g=ft(g>>>0),ht(s>>>0,{name:g,fromWireType:$,argPackAdvance:8,readValueFromPointer:$},{nb:!0})},D:function(s,m){m=ft(m>>>0);var g=m==="std::string";ht(s>>>0,{name:m,fromWireType:function($){var T=se[$>>>2>>>0],B=$+4;if(g)for(var H=B,q=0;q<=T;++q){var te=B+q;if(q==T||K[te>>>0]==0){if(H=je(H,te-H),X===void 0)var X=H;else X+=String.fromCharCode(0),X+=H;H=te+1}}else{for(X=Array(T),q=0;q>>0]);X=X.join("")}return rt($),X},toWireType:function($,T){T instanceof ArrayBuffer&&(T=new Uint8Array(T));var B=typeof T=="string";if(!(B||T instanceof Uint8Array||T instanceof Uint8ClampedArray||T instanceof Int8Array))throw new st("Cannot pass non-string to std::string");var H=g&&B?Wt(T):T.length,q=Nt(4+H+1),te=q+4;if(se[q>>>2>>>0]=H,g&&B)at(T,K,te,H+1);else if(B)for(B=0;B>>0]=X}else for(B=0;B>>0]=T[B];return $!==null&&$.push(rt,q),q},argPackAdvance:8,readValueFromPointer:lr,bb($){rt($)}})},x:function(s,m,g){if(m>>>=0,g>>>=0,g=ft(g),m===2)var $=jr,T=qn,B=Kr,H=q=>he[q>>>1>>>0];else m===4&&($=jn,T=Yr,B=Zr,H=q=>se[q>>>2>>>0]);ht(s>>>0,{name:g,fromWireType:q=>{for(var te=se[q>>>2>>>0],X,de=q+4,Ee=0;Ee<=te;++Ee){var Oe=q+4+Ee*m;(Ee==te||H(Oe)==0)&&(de=$(de,Oe-de),X===void 0?X=de:(X+=String.fromCharCode(0),X+=de),de=Oe+m)}return rt(q),X},toWireType:(q,te)=>{if(typeof te!="string")throw new st(`Cannot pass non-string to C++ string type ${g}`);var X=B(te),de=Nt(4+X+m);return se[de>>>2>>>0]=X/m,T(te,de+4,X+m),q!==null&&q.push(rt,de),de},argPackAdvance:8,readValueFromPointer:lr,bb(q){rt(q)}})},L:function(s,m){m=ft(m>>>0),ht(s>>>0,{ob:!0,name:m,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ha:()=>1,u:function(s,m,g){return m>>>=0,g>>>=0,s=Xe(s>>>0),m=cr(m,"emval::as"),Pr(m,g,s)},w:function(s){return s>>>=0,Rr(()=>(s=Xe(s),s.then(ut)))},n:function(s,m,g,$){return g>>>=0,$>>>=0,s=Xt[s>>>0],m=Xe(m>>>0),s(null,m,g,$)},j:function(s,m,g,$,T){return g>>>=0,$>>>=0,T>>>=0,s=Xt[s>>>0],m=Xe(m>>>0),g=nt(g),s(m,m[g],$,T)},b:dr,A:function(s,m){return m>>>=0,s=Xe(s>>>0),m=Xe(m),s==m},m:function(s){return s>>>=0,s===0?ut(mr()):(s=nt(s),ut(mr()[s]))},i:function(s,m,g){m=Kn(s,m>>>0);var $=m.shift();s--;var T=`return function (obj, func, destructorsRef, args) {\n`,B=0,H=[];g===0&&H.push("obj");for(var q=["retType"],te=[$],X=0;Xde.name).join(", ")}) => ${$.name}>`,Br(wt(g,s))},r:function(s,m){return m>>>=0,s=Xe(s>>>0),m=Xe(m),ut(s[m])},e:function(s){s>>>=0,9>>0);for(var m=Array(s.length),g=0;g>>0))},k:function(){return ut({})},h:function(s){s>>>=0;for(var m=Xe(s);m.length;){var g=m.pop();m.pop()(g)}dr(s)},g:function(s,m,g){m>>>=0,g>>>=0,s=Xe(s>>>0),m=Xe(m),g=Xe(g),s[m]=g},c:function(s,m){return m>>>=0,s=cr(s>>>0,"_emval_take_value"),s=s.readValueFromPointer(m),ut(s)},W:function(s,m){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),W[m>>>2>>>0]=s.getUTCSeconds(),W[m+4>>>2>>>0]=s.getUTCMinutes(),W[m+8>>>2>>>0]=s.getUTCHours(),W[m+12>>>2>>>0]=s.getUTCDate(),W[m+16>>>2>>>0]=s.getUTCMonth(),W[m+20>>>2>>>0]=s.getUTCFullYear()-1900,W[m+24>>>2>>>0]=s.getUTCDay(),W[m+28>>>2>>>0]=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},X:function(s,m){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),W[m>>>2>>>0]=s.getSeconds(),W[m+4>>>2>>>0]=s.getMinutes(),W[m+8>>>2>>>0]=s.getHours(),W[m+12>>>2>>>0]=s.getDate(),W[m+16>>>2>>>0]=s.getMonth(),W[m+20>>>2>>>0]=s.getFullYear()-1900,W[m+24>>>2>>>0]=s.getDay(),W[m+28>>>2>>>0]=(Je(s.getFullYear())?Dr:fr)[s.getMonth()]+s.getDate()-1|0,W[m+36>>>2>>>0]=-(60*s.getTimezoneOffset());var g=new Date(s.getFullYear(),6,1).getTimezoneOffset(),$=new Date(s.getFullYear(),0,1).getTimezoneOffset();W[m+32>>>2>>>0]=(g!=$&&s.getTimezoneOffset()==Math.min($,g))|0},Y:function(s){s>>>=0;var m=new Date(W[s+20>>>2>>>0]+1900,W[s+16>>>2>>>0],W[s+12>>>2>>>0],W[s+8>>>2>>>0],W[s+4>>>2>>>0],W[s>>>2>>>0],0),g=W[s+32>>>2>>>0],$=m.getTimezoneOffset(),T=new Date(m.getFullYear(),6,1).getTimezoneOffset(),B=new Date(m.getFullYear(),0,1).getTimezoneOffset(),H=Math.min(B,T);return 0>g?W[s+32>>>2>>>0]=+(T!=B&&H==$):0>>2>>>0]=m.getDay(),W[s+28>>>2>>>0]=(Je(m.getFullYear())?Dr:fr)[m.getMonth()]+m.getDate()-1|0,W[s>>>2>>>0]=m.getSeconds(),W[s+4>>>2>>>0]=m.getMinutes(),W[s+8>>>2>>>0]=m.getHours(),W[s+12>>>2>>>0]=m.getDate(),W[s+16>>>2>>>0]=m.getMonth(),W[s+20>>>2>>>0]=m.getYear(),s=m.getTime(),BigInt(isNaN(s)?-1:s/1e3)},U:function(){return-52},V:function(){},N:function(s,m,g,$){g>>>=0,$>>>=0;var T=new Date().getFullYear(),B=new Date(T,0,1),H=new Date(T,6,1);T=B.getTimezoneOffset();var q=H.getTimezoneOffset();se[s>>>0>>>2>>>0]=60*Math.max(T,q),W[m>>>0>>>2>>>0]=+(T!=q),s=te=>te.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],B=s(B),H=s(H),q{ne("")},d:function(s,m,g){return s>>>=0,m=hr(m>>>0,g>>>0),Rt[s](...m)},I:function(s,m,g){return s>>>=0,m=hr(m>>>0,g>>>0),Rt[s](...m)},H:()=>Date.now(),O:function(){return 4294901760},q:()=>performance.now(),M:function(s){s>>>=0;var m=K.length;if(4294901760=g;g*=2){var $=m*(1+.2/g);$=Math.min($,s+100663296);var T=Math;$=Math.max(s,$);e:{T=(T.min.call(T,4294901760,$+(65536-$%65536)%65536)-O.buffer.byteLength+65535)/65536;try{O.grow(T),Ae();var B=1;break e}catch{}B=void 0}if(B)return!0}return!1},$:function(s,m){s>>>=0,m>>>=0;var g=0;return ot().forEach(($,T)=>{var B=m+g;for(T=se[s+4*T>>>2>>>0]=B,B=0;B<$.length;++B)N[T++>>>0]=$.charCodeAt(B);N[T>>>0]=0,g+=$.length+1}),0},aa:function(s,m){s>>>=0,m>>>=0;var g=ot();se[s>>>2>>>0]=g.length;var $=0;return g.forEach(T=>$+=T.length+1),se[m>>>2>>>0]=$,0},z:()=>52,F:function(){return 52},_:function(){return 70},E:function(s,m,g,$){m>>>=0,g>>>=0,$>>>=0;for(var T=0,B=0;B>>2>>>0],q=se[m+4>>>2>>>0];m+=8;for(var te=0;te>>0],de=Zn[s];X===0||X===10?((s===1?E:P)(Kt(de,0)),de.length=0):de.push(X)}T+=q}return se[$>>>2>>>0]=T,0},fa:sn,p:function(s,m,g,$){return sn(s>>>0,m>>>0,g>>>0,$>>>0)}},pe=function(){function s(g){return pe=g.exports,pe=Qr(),pe=ln(),O=pe.ja,Ae(),ie.unshift(pe.ka),le--,le==0&&(qe!==null&&(clearInterval(qe),qe=null),G&&(g=G,G=null,g())),pe}var m={a:Qn};if(le++,r.instantiateWasm)try{return r.instantiateWasm(m,s)}catch(g){P(`Module.instantiateWasm callback failed with error: ${g}`),i(g)}return mt(m,function(g){s(g.instance)}).catch(i),{}}(),Mr=s=>(Mr=pe.la)(s);r._OrtInit=(s,m)=>(r._OrtInit=pe.ma)(s,m),r._OrtGetLastError=(s,m)=>(r._OrtGetLastError=pe.na)(s,m),r._OrtCreateSessionOptions=(s,m,g,$,T,B,H,q,te,X)=>(r._OrtCreateSessionOptions=pe.oa)(s,m,g,$,T,B,H,q,te,X),r._OrtAppendExecutionProvider=(s,m)=>(r._OrtAppendExecutionProvider=pe.pa)(s,m),r._OrtAddFreeDimensionOverride=(s,m,g)=>(r._OrtAddFreeDimensionOverride=pe.qa)(s,m,g),r._OrtAddSessionConfigEntry=(s,m,g)=>(r._OrtAddSessionConfigEntry=pe.ra)(s,m,g),r._OrtReleaseSessionOptions=s=>(r._OrtReleaseSessionOptions=pe.sa)(s),r._OrtCreateSession=(s,m,g)=>(r._OrtCreateSession=pe.ta)(s,m,g),r._OrtReleaseSession=s=>(r._OrtReleaseSession=pe.ua)(s),r._OrtGetInputOutputCount=(s,m,g)=>(r._OrtGetInputOutputCount=pe.va)(s,m,g),r._OrtGetInputName=(s,m)=>(r._OrtGetInputName=pe.wa)(s,m),r._OrtGetOutputName=(s,m)=>(r._OrtGetOutputName=pe.xa)(s,m),r._OrtFree=s=>(r._OrtFree=pe.ya)(s),r._OrtCreateTensor=(s,m,g,$,T,B)=>(r._OrtCreateTensor=pe.za)(s,m,g,$,T,B),r._OrtGetTensorData=(s,m,g,$,T)=>(r._OrtGetTensorData=pe.Aa)(s,m,g,$,T),r._OrtReleaseTensor=s=>(r._OrtReleaseTensor=pe.Ba)(s),r._OrtCreateRunOptions=(s,m,g,$)=>(r._OrtCreateRunOptions=pe.Ca)(s,m,g,$),r._OrtAddRunConfigEntry=(s,m,g)=>(r._OrtAddRunConfigEntry=pe.Da)(s,m,g),r._OrtReleaseRunOptions=s=>(r._OrtReleaseRunOptions=pe.Ea)(s),r._OrtCreateBinding=s=>(r._OrtCreateBinding=pe.Fa)(s),r._OrtBindInput=(s,m,g)=>(r._OrtBindInput=pe.Ga)(s,m,g),r._OrtBindOutput=(s,m,g,$)=>(r._OrtBindOutput=pe.Ha)(s,m,g,$),r._OrtClearBoundOutputs=s=>(r._OrtClearBoundOutputs=pe.Ia)(s),r._OrtReleaseBinding=s=>(r._OrtReleaseBinding=pe.Ja)(s),r._OrtRunWithBinding=(s,m,g,$,T)=>(r._OrtRunWithBinding=pe.Ka)(s,m,g,$,T),r._OrtRun=(s,m,g,$,T,B,H,q)=>(r._OrtRun=pe.La)(s,m,g,$,T,B,H,q),r._OrtEndProfiling=s=>(r._OrtEndProfiling=pe.Ma)(s),r._JsepOutput=(s,m,g)=>(r._JsepOutput=pe.Na)(s,m,g),r._JsepGetNodeName=s=>(r._JsepGetNodeName=pe.Oa)(s);var Nt=r._malloc=s=>(Nt=r._malloc=pe.Pa)(s),rt=r._free=s=>(rt=r._free=pe.Qa)(s),yr=s=>(yr=pe.Sa)(s),br=s=>(br=pe.Ta)(s),Ur=()=>(Ur=pe.Ua)(),Jt=s=>(Jt=pe.Wa)(s),dn=()=>(dn=pe.Xa)(),vt=s=>(vt=pe.Ya)(s),ct=()=>(ct=pe.Za)();r.___start_em_js=837952,r.___stop_em_js=838113;function ln(){var s=pe;s=Object.assign({},s);var m=g=>$=>g($)>>>0;return s.la=m(s.la),s.Pa=m(s.Pa),s.Ta=m(s.Ta),s.Ua=(g=>()=>g()>>>0)(s.Ua),s}r.stackSave=()=>Ur(),r.stackRestore=s=>yr(s),r.stackAlloc=s=>br(s),r.UTF8ToString=je,r.stringToUTF8=(s,m,g)=>at(s,K,m,g),r.lengthBytesUTF8=Wt;var Dt;G=function s(){Dt||Vr(),Dt||(G=s)};function Vr(){if(!(0Ii)});var Pi=Wr(()=>{});var ki=Wr(()=>{});var Oi={};gn(Oi,{cpus:()=>ll});var ll,Ri=Y(()=>{ll=void 0});var zi=Wr((Di,mo)=>{"use strict";var Bi=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(t={}){function r(){return ae.buffer!=ue.buffer&&Ne(),ue}function o(){return ae.buffer!=ue.buffer&&Ne(),le}function i(){return ae.buffer!=ue.buffer&&Ne(),qe}function u(){return ae.buffer!=ue.buffer&&Ne(),G}function a(){return ae.buffer!=ue.buffer&&Ne(),ne}function c(){return ae.buffer!=ue.buffer&&Ne(),xe}function p(){return ae.buffer!=ue.buffer&&Ne(),Ke}function h(){return ae.buffer!=ue.buffer&&Ne(),Ut}var d=t,y,w,_=new Promise((n,l)=>{y=n,w=l});d.mountExternalData=(n,l)=>{(d.Db||(d.Db=new Map)).set(n,l)},d.unmountExternalData=()=>{delete d.Db};let v=()=>{let n=(f,b,C)=>(...k)=>{let V=ct,F=b?.();k=f(...k);let re=b?.();return F!==re&&(f=re,C(F),b=C=null),ct!=V?T():k},l=f=>async(...b)=>{try{if(d.Cb)throw Error("Session already started");let C=d.Cb={ec:b[0],errors:[]},k=await f(...b);if(d.Cb!==C)throw Error("Session mismatch");d.Kb?.flush();let V=C.errors;if(0re),0d._OrtCreateSession,f=>d._OrtCreateSession=f),d._OrtRun=l(n(d._OrtRun,()=>d._OrtRun,f=>d._OrtRun=f)),d._OrtRunWithBinding=l(n(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,f=>d._OrtRunWithBinding=f)),d._OrtBindInput=n(d._OrtBindInput,()=>d._OrtBindInput,f=>d._OrtBindInput=f),v=void 0};d.jsepInit=(n,l)=>{if(v?.(),n==="webgpu"){[d.Kb,d.Wb,d.$b,d.Lb,d.Zb,d.ob,d.ac,d.cc,d.Xb,d.Yb,d.bc]=l;let f=d.Kb;d.jsepRegisterBuffer=(b,C,k,V)=>f.registerBuffer(b,C,k,V),d.jsepGetBuffer=b=>f.getBuffer(b),d.jsepCreateDownloader=(b,C,k)=>f.createDownloader(b,C,k),d.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},d.jsepOnRunStart=b=>f.onRunStart(b)}};var S=Object.assign({},d),A="./this.program",I=(n,l)=>{throw l},x=typeof window=="object",E=typeof importScripts=="function",P=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",O=d.ENVIRONMENT_IS_PTHREAD||!1,R="";function L(n){return d.locateFile?d.locateFile(n,R):R+n}var N,K,Q;if(P){var he=(uo(),wr(so)),W=(co(),wr(lo));R=E?W.dirname(R)+"/":__dirname+"/",N=(n,l)=>(n=Wt(n)?new URL(n):W.normalize(n),he.readFileSync(n,l?void 0:"utf8")),Q=n=>(n=N(n,!0),n.buffer||(n=new Uint8Array(n)),n),K=(n,l,f,b=!0)=>{n=Wt(n)?new URL(n):W.normalize(n),he.readFile(n,b?void 0:"utf8",(C,k)=>{C?f(C):l(b?k.buffer:k)})},!d.thisProgram&&1{throw process.exitCode=n,l},global.Worker=Pi().Worker}else(x||E)&&(E?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),typeof e<"u"&&e&&(R=e),R.startsWith("blob:")?R="":R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1),P||(N=n=>{var l=new XMLHttpRequest;return l.open("GET",n,!1),l.send(null),l.responseText},E&&(Q=n=>{var l=new XMLHttpRequest;return l.open("GET",n,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)}),K=(n,l,f)=>{var b=new XMLHttpRequest;b.open("GET",n,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?l(b.response):f()},b.onerror=f,b.send(null)}));P&&typeof performance>"u"&&(global.performance=ki().performance);var se=console.log.bind(console),Ce=console.error.bind(console);P&&(se=(...n)=>he.writeSync(1,n.join(" ")+`\n`),Ce=(...n)=>he.writeSync(2,n.join(" ")+`\n`));var We=se,ee=Ce;Object.assign(d,S),S=null;var ae,Ae,me=!1,ie,ue,le,qe,G,ne,xe,Ke,Be,Ge,Ut;function Ne(){var n=ae.buffer;d.HEAP8=ue=new Int8Array(n),d.HEAP16=qe=new Int16Array(n),d.HEAPU8=le=new Uint8Array(n),d.HEAPU16=G=new Uint16Array(n),d.HEAP32=ne=new Int32Array(n),d.HEAPU32=xe=new Uint32Array(n),d.HEAPF32=Ke=new Float32Array(n),d.HEAPF64=Ut=new Float64Array(n),d.HEAP64=Be=new BigInt64Array(n),d.HEAPU64=Ge=new BigUint64Array(n)}var Ye=16777216;if(O)ae=d.wasmMemory;else if(d.wasmMemory)ae=d.wasmMemory;else if(ae=new WebAssembly.Memory({initial:Ye/65536,maximum:65536,shared:!0}),!(ae.buffer instanceof SharedArrayBuffer))throw ee("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),P&&ee("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ne(),Ye=ae.buffer.byteLength;var mt=[],Rt=[],qt=[],Vt=0,sr=null,jt=null;function xr(){if(Vt--,Vt==0&&(sr!==null&&(clearInterval(sr),sr=null),jt)){var n=jt;jt=null,n()}}function Kt(n){throw n="Aborted("+n+")",ee(n),me=!0,ie=1,n=new WebAssembly.RuntimeError(n+". Build with -sASSERTIONS for more info."),w(n),n}var je=n=>n.startsWith("data:application/octet-stream;base64,"),Wt=n=>n.startsWith("file://"),at;at="ort-wasm-simd-threaded.wasm",je(at)||(at=L(at));function Cr(n){if(Q)return Q(n);throw"both async and sync fetching of the wasm failed"}function ft(n){if(x||E){if(typeof fetch=="function"&&!Wt(n))return fetch(n,{credentials:"same-origin"}).then(l=>{if(!l.ok)throw`failed to load wasm binary file at \'${n}\'`;return l.arrayBuffer()}).catch(()=>Cr(n));if(K)return new Promise((l,f)=>{K(n,b=>l(new Uint8Array(b)),f)})}return Promise.resolve().then(()=>Cr(n))}function ur(n,l,f){return ft(n).then(b=>WebAssembly.instantiate(b,l)).then(f,b=>{ee(`failed to asynchronously prepare wasm: ${b}`),Kt(b)})}function Ar(n,l){var f=at;return typeof WebAssembly.instantiateStreaming!="function"||je(f)||Wt(f)||P||typeof fetch!="function"?ur(f,n,l):fetch(f,{credentials:"same-origin"}).then(b=>WebAssembly.instantiateStreaming(b,n).then(l,function(C){return ee(`wasm streaming compile failed: ${C}`),ee("falling back to ArrayBuffer instantiation"),ur(f,n,l)}))}var Ir={826468:(n,l,f,b)=>{if(typeof d>"u"||!d.Db)return 1;if(n=He(n>>>0),n.startsWith("./")&&(n=n.substring(2)),n=d.Db.get(n),!n)return 2;if(l>>>=0,f>>>=0,b>>>=0,l+f>n.byteLength)return 3;try{return o().set(n.subarray(l,l+f),b>>>0),0}catch{return 4}},826969:()=>{d.Xb()},827e3:()=>{d.Yb()},827029:()=>{d.bc()},827054:n=>d.Wb(n),827087:n=>d.$b(n),827119:(n,l,f)=>{d.Lb(n,l,f,!0)},827158:(n,l,f)=>{d.Lb(n,l,f)},827191:n=>{d.ob("Abs",n,void 0)},827242:n=>{d.ob("Neg",n,void 0)},827293:n=>{d.ob("Floor",n,void 0)},827346:n=>{d.ob("Ceil",n,void 0)},827398:n=>{d.ob("Reciprocal",n,void 0)},827456:n=>{d.ob("Sqrt",n,void 0)},827508:n=>{d.ob("Exp",n,void 0)},827559:n=>{d.ob("Erf",n,void 0)},827610:n=>{d.ob("Sigmoid",n,void 0)},827665:(n,l,f)=>{d.ob("HardSigmoid",n,{alpha:l,beta:f})},827744:n=>{d.ob("Log",n,void 0)},827795:n=>{d.ob("Sin",n,void 0)},827846:n=>{d.ob("Cos",n,void 0)},827897:n=>{d.ob("Tan",n,void 0)},827948:n=>{d.ob("Asin",n,void 0)},828e3:n=>{d.ob("Acos",n,void 0)},828052:n=>{d.ob("Atan",n,void 0)},828104:n=>{d.ob("Sinh",n,void 0)},828156:n=>{d.ob("Cosh",n,void 0)},828208:n=>{d.ob("Asinh",n,void 0)},828261:n=>{d.ob("Acosh",n,void 0)},828314:n=>{d.ob("Atanh",n,void 0)},828367:n=>{d.ob("Tanh",n,void 0)},828419:n=>{d.ob("Not",n,void 0)},828470:(n,l,f)=>{d.ob("Clip",n,{min:l,max:f})},828539:n=>{d.ob("Clip",n,void 0)},828591:(n,l)=>{d.ob("Elu",n,{alpha:l})},828649:n=>{d.ob("Relu",n,void 0)},828701:(n,l)=>{d.ob("LeakyRelu",n,{alpha:l})},828765:(n,l)=>{d.ob("ThresholdedRelu",n,{alpha:l})},828835:(n,l)=>{d.ob("Cast",n,{to:l})},828893:n=>{d.ob("Add",n,void 0)},828944:n=>{d.ob("Sub",n,void 0)},828995:n=>{d.ob("Mul",n,void 0)},829046:n=>{d.ob("Div",n,void 0)},829097:n=>{d.ob("Pow",n,void 0)},829148:n=>{d.ob("Equal",n,void 0)},829201:n=>{d.ob("Greater",n,void 0)},829256:n=>{d.ob("GreaterOrEqual",n,void 0)},829318:n=>{d.ob("Less",n,void 0)},829370:n=>{d.ob("LessOrEqual",n,void 0)},829429:(n,l,f,b,C)=>{d.ob("ReduceMean",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829588:(n,l,f,b,C)=>{d.ob("ReduceMax",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829746:(n,l,f,b,C)=>{d.ob("ReduceMin",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829904:(n,l,f,b,C)=>{d.ob("ReduceProd",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830063:(n,l,f,b,C)=>{d.ob("ReduceSum",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830221:(n,l,f,b,C)=>{d.ob("ReduceL1",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830378:(n,l,f,b,C)=>{d.ob("ReduceL2",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830535:(n,l,f,b,C)=>{d.ob("ReduceLogSum",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830696:(n,l,f,b,C)=>{d.ob("ReduceSumSquare",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830860:(n,l,f,b,C)=>{d.ob("ReduceLogSumExp",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},831024:n=>{d.ob("Where",n,void 0)},831077:(n,l,f)=>{d.ob("Transpose",n,{perm:l?Array.from(a().subarray(l>>>0,f>>>0)):[]})},831185:(n,l,f,b)=>{d.ob("DepthToSpace",n,{blocksize:l,mode:He(f),format:b?"NHWC":"NCHW"})},831318:(n,l,f,b)=>{d.ob("DepthToSpace",n,{blocksize:l,mode:He(f),format:b?"NHWC":"NCHW"})},831451:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we)=>{d.ob("ConvTranspose",n,{format:re?"NHWC":"NCHW",autoPad:l,dilations:[f],group:b,kernelShape:[C],pads:[k,V],strides:[F],wIsConst:()=>!!r()[J>>>0],outputPadding:ce?Array.from(a().subarray(ce>>>0,Re>>>0)):[],outputShape:ze?Array.from(a().subarray(ze>>>0,z>>>0)):[],activation:He(we)})},831852:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z)=>{d.ob("ConvTranspose",n,{format:F?"NHWC":"NCHW",autoPad:l,dilations:Array.from(a().subarray(f>>>0,(f>>>0)+2>>>0)),group:b,kernelShape:Array.from(a().subarray(C>>>0,(C>>>0)+2>>>0)),pads:Array.from(a().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(a().subarray(V>>>0,(V>>>0)+2>>>0)),wIsConst:()=>!!r()[re>>>0],outputPadding:J?Array.from(a().subarray(J>>>0,ce>>>0)):[],outputShape:Re?Array.from(a().subarray(Re>>>0,ze>>>0)):[],activation:He(z)})},832417:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we)=>{d.ob("ConvTranspose",n,{format:re?"NHWC":"NCHW",autoPad:l,dilations:[f],group:b,kernelShape:[C],pads:[k,V],strides:[F],wIsConst:()=>!!r()[J>>>0],outputPadding:ce?Array.from(a().subarray(ce>>>0,Re>>>0)):[],outputShape:ze?Array.from(a().subarray(ze>>>0,z>>>0)):[],activation:He(we)})},832818:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z)=>{d.ob("ConvTranspose",n,{format:F?"NHWC":"NCHW",autoPad:l,dilations:Array.from(a().subarray(f>>>0,(f>>>0)+2>>>0)),group:b,kernelShape:Array.from(a().subarray(C>>>0,(C>>>0)+2>>>0)),pads:Array.from(a().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(a().subarray(V>>>0,(V>>>0)+2>>>0)),wIsConst:()=>!!r()[re>>>0],outputPadding:J?Array.from(a().subarray(J>>>0,ce>>>0)):[],outputShape:Re?Array.from(a().subarray(Re>>>0,ze>>>0)):[],activation:He(z)})},833383:(n,l)=>{d.ob("GlobalAveragePool",n,{format:l?"NHWC":"NCHW"})},833474:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("AveragePool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},833758:(n,l)=>{d.ob("GlobalAveragePool",n,{format:l?"NHWC":"NCHW"})},833849:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("AveragePool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834133:(n,l)=>{d.ob("GlobalMaxPool",n,{format:l?"NHWC":"NCHW"})},834220:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("MaxPool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834500:(n,l)=>{d.ob("GlobalMaxPool",n,{format:l?"NHWC":"NCHW"})},834587:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("MaxPool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834867:(n,l,f,b,C)=>{d.ob("Gemm",n,{alpha:l,beta:f,transA:b,transB:C})},834971:n=>{d.ob("MatMul",n,void 0)},835025:(n,l,f,b)=>{d.ob("ArgMax",n,{keepDims:!!l,selectLastIndex:!!f,axis:b})},835133:(n,l,f,b)=>{d.ob("ArgMin",n,{keepDims:!!l,selectLastIndex:!!f,axis:b})},835241:(n,l)=>{d.ob("Softmax",n,{axis:l})},835304:(n,l)=>{d.ob("Concat",n,{axis:l})},835364:(n,l,f,b,C)=>{d.ob("Split",n,{axis:l,numOutputs:f,splitSizes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},835504:n=>{d.ob("Expand",n,void 0)},835558:(n,l)=>{d.ob("Gather",n,{axis:Number(l)})},835629:(n,l)=>{d.ob("GatherElements",n,{axis:Number(l)})},835708:(n,l,f,b,C,k,V,F,re,J,ce)=>{d.ob("Resize",n,{antialias:l,axes:f?Array.from(a().subarray(f>>>0,b>>>0)):[],coordinateTransformMode:He(C),cubicCoeffA:k,excludeOutside:V,extrapolationValue:F,keepAspectRatioPolicy:He(re),mode:He(J),nearestMode:He(ce)})},836054:(n,l,f,b,C,k,V)=>{d.ob("Slice",n,{starts:l?Array.from(a().subarray(l>>>0,f>>>0)):[],ends:b?Array.from(a().subarray(b>>>0,C>>>0)):[],axes:k?Array.from(a().subarray(k>>>0,V>>>0)):[]})},836270:n=>{d.ob("Tile",n,void 0)},836322:(n,l,f,b)=>{d.ob("LayerNormalization",n,{axis:l,epsilon:f,simplified:!!b})},836433:(n,l,f)=>{d.ob("InstanceNormalization",n,{epsilon:l,format:f?"NHWC":"NCHW"})},836547:(n,l,f)=>{d.ob("InstanceNormalization",n,{epsilon:l,format:f?"NHWC":"NCHW"})},836661:n=>{d.ob("Range",n,void 0)},836714:(n,l)=>{d.ob("Einsum",n,{equation:He(l)})},836795:(n,l,f,b,C)=>{d.ob("Pad",n,{mode:l,value:f,pads:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},836922:(n,l,f,b,C,k)=>{d.ob("BatchNormalization",n,{epsilon:l,momentum:f,spatial:!!C,trainingMode:!!b,format:k?"NHWC":"NCHW"})},837091:(n,l,f,b,C,k)=>{d.ob("BatchNormalization",n,{epsilon:l,momentum:f,spatial:!!C,trainingMode:!!b,format:k?"NHWC":"NCHW"})},837260:(n,l,f)=>{d.ob("CumSum",n,{exclusive:Number(l),reverse:Number(f)})},837357:(n,l,f,b,C,k,V,F,re)=>{d.ob("Attention",n,{numHeads:l,isUnidirectional:f,maskFilterValue:b,scale:C,doRotary:k,qkvHiddenSizes:V?Array.from(a().subarray(Number(F)>>>0,Number(F)+V>>>0)):[],pastPresentShareBuffer:!!re})},837629:n=>{d.ob("BiasAdd",n,void 0)},837684:n=>{d.ob("BiasSplitGelu",n,void 0)},837745:n=>{d.ob("FastGelu",n,void 0)},837801:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze)=>{d.ob("Conv",n,{format:re?"NHWC":"NCHW",auto_pad:l,dilations:[f],group:b,kernel_shape:[C],pads:k?Array.from(a().subarray(k>>>0,V>>>0)):[],strides:[F],w_is_const:()=>!!r()[J>>>0],activation:He(ce),activation_params:Re?Array.from(p().subarray(Re>>>0,ze>>>0)):[]})},838171:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("Conv",n,{format:Re?"NHWC":"NCHW",auto_pad:l,dilations:[f,b],group:C,kernel_shape:[k,V],pads:F?Array.from(a().subarray(F>>>0,re>>>0)):[],strides:[J,ce],w_is_const:()=>!!r()[ze>>>0],activation:He(z),activation_params:we?Array.from(p().subarray(we>>>0,Pe>>>0)):[]})},838562:n=>{d.ob("Gelu",n,void 0)},838614:(n,l,f,b,C,k)=>{d.ob("MatMulNBits",n,{k:l,n:f,accuracyLevel:b,bits:C,blockSize:k})},838741:(n,l,f,b,C,k)=>{d.ob("MultiHeadAttention",n,{numHeads:l,isUnidirectional:f,maskFilterValue:b,scale:C,doRotary:k})},838900:(n,l,f,b,C)=>{d.ob("RotaryEmbedding",n,{interleaved:!!l,numHeads:f,rotaryEmbeddingDim:b,scale:C})},839039:(n,l,f)=>{d.ob("SkipLayerNormalization",n,{epsilon:l,simplified:!!f})},839141:(n,l,f)=>{d.ob("SkipLayerNormalization",n,{epsilon:l,simplified:!!f})},839243:(n,l,f,b)=>{d.ob("LayerNormalization",n,{axis:l,epsilon:f,simplified:!!b})},839354:n=>{d.ac(n)},839388:(n,l)=>d.cc(n,l,d.Cb.ec,d.Cb.errors)};function st(n){this.name="ExitStatus",this.message=`Program terminated with exit(${n})`,this.status=n}var Tr=n=>{n.terminate(),n.onmessage=()=>{}},ht=n=>{ge.xb.length==0&&(lr(),ge.Mb(ge.xb[0]));var l=ge.xb.pop();if(!l)return 6;ge.yb.push(l),ge.ub[n.wb]=l,l.wb=n.wb;var f={cmd:"run",start_routine:n.fc,arg:n.Rb,pthread_ptr:n.wb};return P&&l.unref(),l.postMessage(f,n.mc),0},bt=0,Er=n=>{var l=io();return n=n(),fn(l),n},Te=(n,l,...f)=>Er(()=>{for(var b=2*f.length,C=oo(8*b),k=C>>>3,V=0;V>>0]=F)}return gi(n,0,b,C,l)});function dr(n){if(O)return Te(0,1,n);ie=n,0{if(ie=n,O)throw jr(n),"unwind";dr(n)};function ut(){for(var n=d.numThreads;n--;)lr();mt.unshift(()=>{Vt++,Fn(()=>xr())})}function lr(){var n=L("ort-wasm-simd-threaded.worker.js");n=new Worker(n),ge.xb.push(n)}function Fn(n){O?n():Promise.all(ge.xb.map(ge.Mb)).then(n)}var ge={xb:[],yb:[],Qb:[],ub:{},Gb(){O?(ge.receiveObjectTransfer=ge.dc,ge.threadInitTLS=ge.Pb,ge.setExitStatus=ge.Ob):ut()},Ob:n=>ie=n,pc:["$terminateWorker"],hc:()=>{for(var n of ge.yb)Tr(n);for(n of ge.xb)Tr(n);ge.xb=[],ge.yb=[],ge.ub=[]},Nb:n=>{var l=n.wb;delete ge.ub[l],ge.xb.push(n),ge.yb.splice(ge.yb.indexOf(n),1),n.wb=0,ro(l)},dc(){},Pb(){ge.Qb.forEach(n=>n())},Mb:n=>new Promise(l=>{n.onmessage=k=>{k=k.data;var V=k.cmd;if(k.targetThread&&k.targetThread!=pn()){var F=ge.ub[k.targetThread];F?F.postMessage(k,k.transferList):ee(`Internal error! Worker sent a message "${V}" to target pthread ${k.targetThread}, but that thread no longer exists!`)}else V==="checkMailbox"?rt():V==="spawnThread"?ht(k):V==="cleanupThread"?ge.Nb(ge.ub[k.thread]):V==="killThread"?(k=k.thread,V=ge.ub[k],delete ge.ub[k],Tr(V),ro(k),ge.yb.splice(ge.yb.indexOf(V),1),V.wb=0):V==="cancelThread"?ge.ub[k.thread].postMessage({cmd:"cancel"}):V==="loaded"?(n.loaded=!0,P&&!n.wb&&n.unref(),l(n)):V==="alert"?alert(`Thread ${k.threadId}: ${k.text}`):k.target==="setimmediate"?n.postMessage(k):V==="callHandler"?d[k.handler](...k.args):V&&ee(`worker sent an unknown command ${V}`)},n.onerror=k=>{throw ee(`worker sent an error! ${k.filename}:${k.lineno}: ${k.message}`),k},P&&(n.on("message",k=>n.onmessage({data:k})),n.on("error",k=>n.onerror(k)));var f=[],b=["onExit"],C;for(C of b)d.hasOwnProperty(C)&&f.push(C);n.postMessage({cmd:"load",handlers:f,urlOrBlob:d.mainScriptUrlOrBlob||e,wasmMemory:ae,wasmModule:Ae})})};d.PThread=ge;var Yt=n=>{for(;0{var n=pn(),l=c()[n+52>>>2>>>0];n=c()[n+56>>>2>>>0],bi(l,l-n),fn(l)};function jr(n){if(O)return Te(1,0,n);Xe(n)}d.invokeEntryPoint=(n,l)=>{bt=0,n=wi(n,l),0>>2>>>0]=0,c()[this.Ib+4>>>2>>>0]=l,c()[this.Ib+8>>>2>>>0]=f}}var Kr=0,jn=0;function Yr(n,l,f,b){return O?Te(2,1,n,l,f,b):Zr(n,l,f,b)}function Zr(n,l,f,b){if(n>>>=0,l>>>=0,f>>>=0,b>>>=0,typeof SharedArrayBuffer>"u")return ee("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var C=[];return O&&C.length===0?Yr(n,l,f,b):(n={fc:f,wb:n,Rb:b,mc:C},O?(n.oc="spawnThread",postMessage(n,C),0):ht(n))}var cr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Pr=(n,l,f)=>{l>>>=0;var b=l+f;for(f=l;n[f]&&!(f>=b);)++f;if(16C?b+=String.fromCharCode(C):(C-=65536,b+=String.fromCharCode(55296|C>>10,56320|C&1023))}}else b+=String.fromCharCode(C)}return b},He=(n,l)=>(n>>>=0)?Pr(o(),n,l):"";function Xr(n,l,f){return O?Te(3,1,n,l,f):0}function Qr(n,l){if(O)return Te(4,1,n,l)}var gt=n=>{for(var l=0,f=0;f=b?l++:2047>=b?l+=2:55296<=b&&57343>=b?(l+=4,++f):l+=3}return l},dt=(n,l,f,b)=>{if(f>>>=0,!(0=V){var F=n.charCodeAt(++k);V=65536+((V&1023)<<10)|F&1023}if(127>=V){if(f>=b)break;l[f++>>>0]=V}else{if(2047>=V){if(f+1>=b)break;l[f++>>>0]=192|V>>6}else{if(65535>=V){if(f+2>=b)break;l[f++>>>0]=224|V>>12}else{if(f+3>=b)break;l[f++>>>0]=240|V>>18,l[f++>>>0]=128|V>>12&63}l[f++>>>0]=128|V>>6&63}l[f++>>>0]=128|V&63}}return l[f>>>0]=0,f-C},Bt=(n,l,f)=>dt(n,o(),l,f);function Zt(n,l){if(O)return Te(5,1,n,l)}function kr(n,l,f){if(O)return Te(6,1,n,l,f)}function Or(n,l,f){return O?Te(7,1,n,l,f):0}function Jr(n,l){if(O)return Te(8,1,n,l)}function pr(n,l,f){if(O)return Te(9,1,n,l,f)}function en(n,l,f,b){if(O)return Te(10,1,n,l,f,b)}function tn(n,l,f,b){if(O)return Te(11,1,n,l,f,b)}function rn(n,l,f,b){if(O)return Te(12,1,n,l,f,b)}function nn(n){if(O)return Te(13,1,n)}function Rr(n,l){if(O)return Te(14,1,n,l)}function Xt(n,l,f){if(O)return Te(15,1,n,l,f)}var on,nt=n=>{for(var l="";o()[n>>>0];)l+=on[o()[n++>>>0]];return l},mr={},Br={},Kn={},wt;function Yn(n,l,f={}){var b=l.name;if(!n)throw new wt(`type "${b}" must have a positive integer typeid pointer`);if(Br.hasOwnProperty(n)){if(f.Ub)return;throw new wt(`Cannot register type \'${b}\' twice`)}Br[n]=l,delete Kn[n],mr.hasOwnProperty(n)&&(l=mr[n],delete mr[n],l.forEach(C=>C()))}function Je(n,l,f={}){if(!("argPackAdvance"in l))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Yn(n,l,f)}var Dr=(n,l,f)=>{switch(l){case 1:return f?b=>r()[b>>>0]:b=>o()[b>>>0];case 2:return f?b=>i()[b>>>1>>>0]:b=>u()[b>>>1>>>0];case 4:return f?b=>a()[b>>>2>>>0]:b=>c()[b>>>2>>>0];case 8:return f?b=>Be[b>>>3]:b=>Ge[b>>>3];default:throw new TypeError(`invalid integer width (${l}): ${n}`)}},fr=[],lt=[];function hr(n){n>>>=0,9{if(!n)throw new wt("Cannot use deleted val. handle = "+n);return lt[n]},ot=n=>{switch(n){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let l=fr.pop()||lt.length;return lt[l]=n,lt[l+1]=1,l}};function Qt(n){return this.fromWireType(c()[n>>>2>>>0])}var Zn={name:"emscripten::val",fromWireType:n=>{var l=Qe(n);return hr(n),l},toWireType:(n,l)=>ot(l),argPackAdvance:8,readValueFromPointer:Qt,Bb:null},an=(n,l)=>{switch(l){case 4:return function(f){return this.fromWireType(p()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(h()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${l}): ${n}`)}},zr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Xn=(n,l)=>{for(var f=n>>1,b=f+l/2;!(f>=b)&&u()[f>>>0];)++f;if(f<<=1,32=l/2);++b){var C=i()[n+2*b>>>1>>>0];if(C==0)break;f+=String.fromCharCode(C)}return f},sn=(n,l,f)=>{if(f??=2147483647,2>f)return 0;f-=2;var b=l;f=f<2*n.length?f/2:n.length;for(var C=0;C>>1>>>0]=k,l+=2}return i()[l>>>1>>>0]=0,l-b},un=n=>2*n.length,gr=(n,l)=>{for(var f=0,b="";!(f>=l/4);){var C=a()[n+4*f>>>2>>>0];if(C==0)break;++f,65536<=C?(C-=65536,b+=String.fromCharCode(55296|C>>10,56320|C&1023)):b+=String.fromCharCode(C)}return b},Qn=(n,l,f)=>{if(l>>>=0,f??=2147483647,4>f)return 0;var b=l;f=b+f-4;for(var C=0;C=k){var V=n.charCodeAt(++C);k=65536+((k&1023)<<10)|V&1023}if(a()[l>>>2>>>0]=k,l+=4,l+4>f)break}return a()[l>>>2>>>0]=0,l-b},pe=n=>{for(var l=0,f=0;f=b&&++f,l+=4}return l},Mr=n=>{if(!me)try{if(n(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(a(),n>>>2,n).value.then(rt),n+=128,Atomics.store(a(),n>>>2,1))}d.__emscripten_thread_mailbox_await=Nt;var rt=()=>{var n=pn();n&&(Nt(n),Mr(yi))};d.checkMailbox=rt;var yr=[],br=(n,l)=>{var f=Br[n];if(f===void 0)throw n=fi(n),f=nt(n),At(n),new wt(`${l} has unknown type ${f}`);return f},Ur=(n,l,f)=>{var b=[];return n=n.toWireType(b,f),b.length&&(c()[l>>>2>>>0]=ot(b)),n},Jt=n=>{try{n()}catch(l){Kt(l)}};function dn(){var n=oe,l={};for(let[f,b]of Object.entries(n))l[f]=typeof b=="function"?(...C)=>{Dt.push(f);try{return b(...C)}finally{me||(Dt.pop(),ct&&vt===1&&Dt.length===0&&(vt=0,bt+=1,Jt($i),typeof Fibers<"u"&&Fibers.rc()))}}:b;return l}var vt=0,ct=null,ln=0,Dt=[],Vr={},s={},m=0,g=null,$=[];function T(){return new Promise((n,l)=>{g={resolve:n,reject:l}})}function B(){var n=mn(65548),l=n+12;c()[n>>>2>>>0]=l,c()[n+4>>>2>>>0]=l+65536,l=Dt[0];var f=Vr[l];return f===void 0&&(f=m++,Vr[l]=f,s[f]=l),l=f,a()[n+8>>>2>>>0]=l,n}function H(){var n=a()[ct+8>>>2>>>0];return n=oe[s[n]],--bt,n()}function q(n){if(!me){if(vt===0){var l=!1,f=!1;n((b=0)=>{if(!me&&(ln=b,l=!0,f)){vt=2,Jt(()=>_i(ct)),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.resume(),b=!1;try{var C=H()}catch(F){C=F,b=!0}var k=!1;if(!ct){var V=g;V&&(g=null,(b?V.reject:V.resolve)(C),k=!0)}if(b&&!k)throw C}}),f=!0,l||(vt=1,ct=B(),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.pause(),Jt(()=>vi(ct)))}else vt===2?(vt=0,Jt(Si),At(ct),ct=null,$.forEach(Mr)):Kt(`invalid state: ${vt}`);return ln}}function te(n){return q(l=>{n().then(l)})}var X=[],de={},Ee=n=>{var l=de[n];return l===void 0?nt(n):l},Oe=()=>typeof globalThis=="object"?globalThis:Function("return this")(),D=n=>{var l=X.length;return X.push(n),l},be=(n,l)=>{for(var f=Array(n),b=0;b>>2>>>0],"parameter "+b);return f},Ie=(n,l)=>Object.defineProperty(l,"name",{value:n});function zt(n){var l=Function;if(!(l instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof l} which is not a function`);var f=Ie(l.name||"unknownFunctionName",function(){});return f.prototype=l.prototype,f=new f,n=l.apply(f,n),n instanceof Object?n:f}var Mt=n=>n%4===0&&(n%100!==0||n%400===0),Qo=[0,31,60,91,121,152,182,213,244,274,305,335],Jo=[0,31,59,90,120,151,181,212,243,273,304,334];function ei(n,l,f,b,C,k,V){return O?Te(16,1,n,l,f,b,C,k,V):-52}function ti(n,l,f,b,C,k){if(O)return Te(17,1,n,l,f,b,C,k)}var Jn=[],ri=(n,l)=>{Jn.length=0;for(var f;f=o()[n++>>>0];){var b=f!=105;b&=f!=112,l+=b&&l%8?4:0,Jn.push(f==112?c()[l>>>2>>>0]:f==106?Be[l>>>3]:f==105?a()[l>>>2>>>0]:h()[l>>>3>>>0]),l+=b?8:4}return Jn},eo={},ni=()=>{if(!to){var n={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:A||"./this.program"},l;for(l in eo)eo[l]===void 0?delete n[l]:n[l]=eo[l];var f=[];for(l in n)f.push(`${l}=${n[l]}`);to=f}return to},to;function oi(n,l){if(O)return Te(18,1,n,l);n>>>=0,l>>>=0;var f=0;return ni().forEach((b,C)=>{var k=l+f;for(C=c()[n+4*C>>>2>>>0]=k,k=0;k>>0]=b.charCodeAt(k);r()[C>>>0]=0,f+=b.length+1}),0}function ii(n,l){if(O)return Te(19,1,n,l);n>>>=0,l>>>=0;var f=ni();c()[n>>>2>>>0]=f.length;var b=0;return f.forEach(C=>b+=C.length+1),c()[l>>>2>>>0]=b,0}function ai(n){return O?Te(20,1,n):52}function si(n,l,f,b){return O?Te(21,1,n,l,f,b):52}function ui(n,l,f,b){return O?Te(22,1,n,l,f,b):70}var Xd=[null,[],[]];function di(n,l,f,b){if(O)return Te(23,1,n,l,f,b);l>>>=0,f>>>=0,b>>>=0;for(var C=0,k=0;k>>2>>>0],F=c()[l+4>>>2>>>0];l+=8;for(var re=0;re>>0],ce=Xd[n];J===0||J===10?((n===1?We:ee)(Pr(ce,0)),ce.length=0):ce.push(J)}C+=F}return c()[b>>>2>>>0]=C,0}var li=[31,29,31,30,31,30,31,31,30,31,30,31],ci=[31,28,31,30,31,30,31,31,30,31,30,31];function Qd(n){var l=Array(gt(n)+1);return dt(n,l,0,l.length),l}var Jd=(n,l)=>{r().set(n,l>>>0)};function pi(n,l,f,b){function C(z,we,Pe){for(z=typeof z=="number"?z.toString():z||"";z.lengthCi?-1:0er-z.getDate())we-=er-z.getDate()+1,z.setDate(1),11>Pe?z.setMonth(Pe+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1));else{z.setDate(z.getDate()+we);break}}return Pe=new Date(z.getFullYear()+1,0,4),we=F(new Date(z.getFullYear(),0,4)),Pe=F(Pe),0>=V(we,z)?0>=V(Pe,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}n>>>=0,l>>>=0,f>>>=0,b>>>=0;var J=c()[b+40>>>2>>>0];b={kc:a()[b>>>2>>>0],jc:a()[b+4>>>2>>>0],Eb:a()[b+8>>>2>>>0],Jb:a()[b+12>>>2>>>0],Fb:a()[b+16>>>2>>>0],Ab:a()[b+20>>>2>>>0],vb:a()[b+24>>>2>>>0],zb:a()[b+28>>>2>>>0],qc:a()[b+32>>>2>>>0],ic:a()[b+36>>>2>>>0],lc:J?He(J):""},f=He(f),J={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var ce in J)f=f.replace(new RegExp(ce,"g"),J[ce]);var Re="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ze="January February March April May June July August September October November December".split(" ");J={"%a":z=>Re[z.vb].substring(0,3),"%A":z=>Re[z.vb],"%b":z=>ze[z.Fb].substring(0,3),"%B":z=>ze[z.Fb],"%C":z=>k((z.Ab+1900)/100|0,2),"%d":z=>k(z.Jb,2),"%e":z=>C(z.Jb,2," "),"%g":z=>re(z).toString().substring(2),"%G":re,"%H":z=>k(z.Eb,2),"%I":z=>(z=z.Eb,z==0?z=12:12{for(var we=0,Pe=0;Pe<=z.Fb-1;we+=(Mt(z.Ab+1900)?li:ci)[Pe++]);return k(z.Jb+we,3)},"%m":z=>k(z.Fb+1,2),"%M":z=>k(z.jc,2),"%n":()=>`\n`,"%p":z=>0<=z.Eb&&12>z.Eb?"AM":"PM","%S":z=>k(z.kc,2),"%t":()=>" ","%u":z=>z.vb||7,"%U":z=>k(Math.floor((z.zb+7-z.vb)/7),2),"%V":z=>{var we=Math.floor((z.zb+7-(z.vb+6)%7)/7);if(2>=(z.vb+371-z.zb-2)%7&&we++,we)we==53&&(Pe=(z.vb+371-z.zb)%7,Pe==4||Pe==3&&Mt(z.Ab)||(we=1));else{we=52;var Pe=(z.vb+7-z.zb-1)%7;(Pe==4||Pe==5&&Mt(z.Ab%400-1))&&we++}return k(we,2)},"%w":z=>z.vb,"%W":z=>k(Math.floor((z.zb+7-(z.vb+6)%7)/7),2),"%y":z=>(z.Ab+1900).toString().substring(2),"%Y":z=>z.Ab+1900,"%z":z=>{z=z.ic;var we=0<=z;return z=Math.abs(z)/60,(we?"+":"-")+("0000"+(z/60*100+z%60)).slice(-4)},"%Z":z=>z.lc,"%%":()=>"%"},f=f.replace(/%%/g,"\\0\\0");for(ce in J)f.includes(ce)&&(f=f.replace(new RegExp(ce,"g"),J[ce](b)));return f=f.replace(/\\0\\0/g,"%"),ce=Qd(f),ce.length>l?0:(Jd(ce,n),ce.length-1)}ge.Gb();for(var mi=Array(256),cn=0;256>cn;++cn)mi[cn]=String.fromCharCode(cn);on=mi,wt=d.BindingError=class extends Error{constructor(n){super(n),this.name="BindingError"}},d.InternalError=class extends Error{constructor(n){super(n),this.name="InternalError"}},lt.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>lt.length/2-5-fr.length;var el=[dr,jr,Yr,Xr,Qr,Zt,kr,Or,Jr,pr,en,tn,rn,nn,Rr,Xt,ei,ti,oi,ii,ai,si,ui,di],tl={ua:function(n,l,f){return te(async()=>{await d.Zb(n,l,f)})},b:function(n,l,f){throw n>>>=0,new qn(n).Gb(l>>>0,f>>>0),Kr=n,jn++,Kr},ia:function(n){hi(n>>>0,!E,1,!x,131072,!1),ge.Pb()},G:function(n){n>>>=0,O?postMessage({cmd:"cleanupThread",thread:n}):ge.Nb(ge.ub[n])},_:Zr,A:Xr,pa:Qr,W:Zt,Y:kr,qa:Or,na:Jr,fa:pr,ma:en,K:tn,X:rn,U:nn,oa:Rr,V:Xt,E:function(n,l,f){n>>>=0,f>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:b=>b,toWireType:function(b,C){if(typeof C!="bigint"&&typeof C!="number")throw C===null?C="null":(b=typeof C,C=b==="object"||b==="array"||b==="function"?C.toString():""+C),new TypeError(`Cannot convert "${C}" to ${this.name}`);return typeof C=="number"&&(C=BigInt(C)),C},argPackAdvance:8,readValueFromPointer:Dr(l,f,l.indexOf("u")==-1),Bb:null})},O:function(n,l,f,b){n>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:function(C){return!!C},toWireType:function(C,k){return k?f:b},argPackAdvance:8,readValueFromPointer:function(C){return this.fromWireType(o()[C>>>0])},Bb:null})},N:function(n){return Je(n>>>0,Zn)},D:function(n,l,f){n>>>=0,f>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:b=>b,toWireType:(b,C)=>C,argPackAdvance:8,readValueFromPointer:an(l,f),Bb:null})},t:function(n,l,f,b,C){if(n>>>=0,f>>>=0,l=nt(l>>>0),C===-1&&(C=4294967295),C=F=>F,b===0){var k=32-8*f;C=F=>F<>>k}var V=l.includes("unsigned")?function(F,re){return re>>>0}:function(F,re){return re};Je(n,{name:l,fromWireType:C,toWireType:V,argPackAdvance:8,readValueFromPointer:Dr(l,f,b!==0),Bb:null})},p:function(n,l,f){function b(k){var V=c()[k>>>2>>>0];return k=c()[k+4>>>2>>>0],new C(r().buffer,k,V)}n>>>=0;var C=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][l];f=nt(f>>>0),Je(n,{name:f,fromWireType:b,argPackAdvance:8,readValueFromPointer:b},{Ub:!0})},F:function(n,l){n>>>=0,l=nt(l>>>0);var f=l==="std::string";Je(n,{name:l,fromWireType:function(b){var C=c()[b>>>2>>>0],k=b+4;if(f)for(var V=k,F=0;F<=C;++F){var re=k+F;if(F==C||o()[re>>>0]==0){if(V=He(V,re-V),J===void 0)var J=V;else J+=String.fromCharCode(0),J+=V;V=re+1}}else{for(J=Array(C),F=0;F>>0]);J=J.join("")}return At(b),J},toWireType:function(b,C){C instanceof ArrayBuffer&&(C=new Uint8Array(C));var k=typeof C=="string";if(!(k||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array))throw new wt("Cannot pass non-string to std::string");var V=f&&k?gt(C):C.length,F=mn(4+V+1),re=F+4;if(c()[F>>>2>>>0]=V,f&&k)Bt(C,re,V+1);else if(k)for(k=0;k>>0]=J}else for(k=0;k>>0]=C[k];return b!==null&&b.push(At,F),F},argPackAdvance:8,readValueFromPointer:Qt,Bb(b){At(b)}})},z:function(n,l,f){if(n>>>=0,l>>>=0,f>>>=0,f=nt(f),l===2)var b=Xn,C=sn,k=un,V=F=>u()[F>>>1>>>0];else l===4&&(b=gr,C=Qn,k=pe,V=F=>c()[F>>>2>>>0]);Je(n,{name:f,fromWireType:F=>{for(var re=c()[F>>>2>>>0],J,ce=F+4,Re=0;Re<=re;++Re){var ze=F+4+Re*l;(Re==re||V(ze)==0)&&(ce=b(ce,ze-ce),J===void 0?J=ce:(J+=String.fromCharCode(0),J+=ce),ce=ze+l)}return At(F),J},toWireType:(F,re)=>{if(typeof re!="string")throw new wt(`Cannot pass non-string to C++ string type ${f}`);var J=k(re),ce=mn(4+J+l);return c()[ce>>>2>>>0]=J/l,C(re,ce+4,J+l),F!==null&&F.push(At,ce),ce},argPackAdvance:8,readValueFromPointer:Qt,Bb(F){At(F)}})},P:function(n,l){n>>>=0,l=nt(l>>>0),Je(n,{Vb:!0,name:l,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ta:()=>1,S:function(n,l){n>>>=0,n==l>>>0?setTimeout(rt):O?postMessage({targetThread:n,cmd:"checkMailbox"}):(n=ge.ub[n])&&n.postMessage({cmd:"checkMailbox"})},$:function(n,l,f,b,C){l>>>=0,f>>>=0,b/=2,yr.length=b,C=C>>>0>>>3;for(var k=0;k>>0];return n=l?Ir[l]:el[n],ge.Sb=f,f=n(...yr),ge.Sb=0,f},ha:Nt,sa:function(n){P&&ge.ub[n>>>0].ref()},w:function(n,l,f){return l>>>=0,f>>>=0,n=Qe(n>>>0),l=br(l,"emval::as"),Ur(l,f,n)},y:function(n){return n>>>=0,te(()=>(n=Qe(n),n.then(ot)))},o:function(n,l,f,b){return f>>>=0,b>>>=0,n=X[n>>>0],l=Qe(l>>>0),n(null,l,f,b)},k:function(n,l,f,b,C){return f>>>=0,b>>>=0,C>>>=0,n=X[n>>>0],l=Qe(l>>>0),f=Ee(f),n(l,l[f],b,C)},c:hr,C:function(n,l){return l>>>=0,n=Qe(n>>>0),l=Qe(l),n==l},n:function(n){return n>>>=0,n===0?ot(Oe()):(n=Ee(n),ot(Oe()[n]))},j:function(n,l,f){l=be(n,l>>>0);var b=l.shift();n--;var C=`return function (obj, func, destructorsRef, args) {\n`,k=0,V=[];f===0&&V.push("obj");for(var F=["retType"],re=[b],J=0;Jce.name).join(", ")}) => ${b.name}>`,D(Ie(f,n))},s:function(n,l){return l>>>=0,n=Qe(n>>>0),l=Qe(l),ot(n[l])},d:function(n){n>>>=0,9>>0);for(var l=Array(n.length),f=0;f>>0))},l:function(){return ot({})},i:function(n){n>>>=0;for(var l=Qe(n);l.length;){var f=l.pop();l.pop()(f)}hr(n)},h:function(n,l,f){l>>>=0,f>>>=0,n=Qe(n>>>0),l=Qe(l),f=Qe(f),n[l]=f},e:function(n,l){return l>>>=0,n=br(n>>>0,"_emval_take_value"),n=n.readValueFromPointer(l),ot(n)},ca:function(n,l){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),a()[l>>>2>>>0]=n.getUTCSeconds(),a()[l+4>>>2>>>0]=n.getUTCMinutes(),a()[l+8>>>2>>>0]=n.getUTCHours(),a()[l+12>>>2>>>0]=n.getUTCDate(),a()[l+16>>>2>>>0]=n.getUTCMonth(),a()[l+20>>>2>>>0]=n.getUTCFullYear()-1900,a()[l+24>>>2>>>0]=n.getUTCDay(),n=(n.getTime()-Date.UTC(n.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[l+28>>>2>>>0]=n},da:function(n,l){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),a()[l>>>2>>>0]=n.getSeconds(),a()[l+4>>>2>>>0]=n.getMinutes(),a()[l+8>>>2>>>0]=n.getHours(),a()[l+12>>>2>>>0]=n.getDate(),a()[l+16>>>2>>>0]=n.getMonth(),a()[l+20>>>2>>>0]=n.getFullYear()-1900,a()[l+24>>>2>>>0]=n.getDay();var f=(Mt(n.getFullYear())?Qo:Jo)[n.getMonth()]+n.getDate()-1|0;a()[l+28>>>2>>>0]=f,a()[l+36>>>2>>>0]=-(60*n.getTimezoneOffset()),f=new Date(n.getFullYear(),6,1).getTimezoneOffset();var b=new Date(n.getFullYear(),0,1).getTimezoneOffset();n=(f!=b&&n.getTimezoneOffset()==Math.min(b,f))|0,a()[l+32>>>2>>>0]=n},ea:function(n){n>>>=0;var l=new Date(a()[n+20>>>2>>>0]+1900,a()[n+16>>>2>>>0],a()[n+12>>>2>>>0],a()[n+8>>>2>>>0],a()[n+4>>>2>>>0],a()[n>>>2>>>0],0),f=a()[n+32>>>2>>>0],b=l.getTimezoneOffset(),C=new Date(l.getFullYear(),6,1).getTimezoneOffset(),k=new Date(l.getFullYear(),0,1).getTimezoneOffset(),V=Math.min(k,C);return 0>f?a()[n+32>>>2>>>0]=+(C!=k&&V==b):0>>2>>>0]=l.getDay(),f=(Mt(l.getFullYear())?Qo:Jo)[l.getMonth()]+l.getDate()-1|0,a()[n+28>>>2>>>0]=f,a()[n>>>2>>>0]=l.getSeconds(),a()[n+4>>>2>>>0]=l.getMinutes(),a()[n+8>>>2>>>0]=l.getHours(),a()[n+12>>>2>>>0]=l.getDate(),a()[n+16>>>2>>>0]=l.getMonth(),a()[n+20>>>2>>>0]=l.getYear(),n=l.getTime(),BigInt(isNaN(n)?-1:n/1e3)},aa:ei,ba:ti,R:function(n,l,f,b){n>>>=0,l>>>=0,f>>>=0,b>>>=0;var C=new Date().getFullYear(),k=new Date(C,0,1),V=new Date(C,6,1);C=k.getTimezoneOffset();var F=V.getTimezoneOffset(),re=Math.max(C,F);c()[n>>>2>>>0]=60*re,a()[l>>>2>>>0]=+(C!=F),n=J=>J.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],k=n(k),V=n(V),F{Kt("")},f:function(n,l,f){return n>>>=0,l=ri(l>>>0,f>>>0),Ir[n](...l)},M:function(n,l,f){return n>>>=0,l=ri(l>>>0,f>>>0),Ir[n](...l)},H:()=>{},L:()=>Date.now(),ra:()=>{throw bt+=1,"unwind"},T:function(){return 4294901760},u:()=>performance.timeOrigin+performance.now(),x:()=>P?(Ri(),wr(Oi)).cpus().length:navigator.hardwareConcurrency,Q:function(n){n>>>=0;var l=o().length;if(n<=l||4294901760=f;f*=2){var b=l*(1+.2/f);b=Math.min(b,n+100663296);var C=Math;b=Math.max(n,b);e:{C=(C.min.call(C,4294901760,b+(65536-b%65536)%65536)-ae.buffer.byteLength+65535)/65536;try{ae.grow(C),Ne();var k=1;break e}catch{}k=void 0}if(k)return!0}return!1},ja:oi,la:ii,Z:Xe,B:ai,J:si,ga:ui,I:di,a:ae||d.wasmMemory,ka:pi,r:function(n,l,f,b){return pi(n>>>0,l>>>0,f>>>0,b>>>0)}},oe=function(){function n(f,b){return oe=f.exports,oe=dn(),oe=rl(),ge.Qb.push(oe.cb),Rt.unshift(oe.va),Ae=b,xr(),oe}var l={a:tl};if(Vt++,d.instantiateWasm)try{return d.instantiateWasm(l,n)}catch(f){ee(`Module.instantiateWasm callback failed with error: ${f}`),w(f)}return Ar(l,function(f){n(f.instance,f.module)}).catch(w),{}}(),fi=n=>(fi=oe.wa)(n);d.__embind_initialize_bindings=()=>(d.__embind_initialize_bindings=oe.xa)(),d._OrtInit=(n,l)=>(d._OrtInit=oe.ya)(n,l),d._OrtGetLastError=(n,l)=>(d._OrtGetLastError=oe.za)(n,l),d._OrtCreateSessionOptions=(n,l,f,b,C,k,V,F,re,J)=>(d._OrtCreateSessionOptions=oe.Aa)(n,l,f,b,C,k,V,F,re,J),d._OrtAppendExecutionProvider=(n,l)=>(d._OrtAppendExecutionProvider=oe.Ba)(n,l),d._OrtAddFreeDimensionOverride=(n,l,f)=>(d._OrtAddFreeDimensionOverride=oe.Ca)(n,l,f),d._OrtAddSessionConfigEntry=(n,l,f)=>(d._OrtAddSessionConfigEntry=oe.Da)(n,l,f),d._OrtReleaseSessionOptions=n=>(d._OrtReleaseSessionOptions=oe.Ea)(n),d._OrtCreateSession=(n,l,f)=>(d._OrtCreateSession=oe.Fa)(n,l,f),d._OrtReleaseSession=n=>(d._OrtReleaseSession=oe.Ga)(n),d._OrtGetInputOutputCount=(n,l,f)=>(d._OrtGetInputOutputCount=oe.Ha)(n,l,f),d._OrtGetInputName=(n,l)=>(d._OrtGetInputName=oe.Ia)(n,l),d._OrtGetOutputName=(n,l)=>(d._OrtGetOutputName=oe.Ja)(n,l),d._OrtFree=n=>(d._OrtFree=oe.Ka)(n),d._OrtCreateTensor=(n,l,f,b,C,k)=>(d._OrtCreateTensor=oe.La)(n,l,f,b,C,k),d._OrtGetTensorData=(n,l,f,b,C)=>(d._OrtGetTensorData=oe.Ma)(n,l,f,b,C),d._OrtReleaseTensor=n=>(d._OrtReleaseTensor=oe.Na)(n),d._OrtCreateRunOptions=(n,l,f,b)=>(d._OrtCreateRunOptions=oe.Oa)(n,l,f,b),d._OrtAddRunConfigEntry=(n,l,f)=>(d._OrtAddRunConfigEntry=oe.Pa)(n,l,f),d._OrtReleaseRunOptions=n=>(d._OrtReleaseRunOptions=oe.Qa)(n),d._OrtCreateBinding=n=>(d._OrtCreateBinding=oe.Ra)(n),d._OrtBindInput=(n,l,f)=>(d._OrtBindInput=oe.Sa)(n,l,f),d._OrtBindOutput=(n,l,f,b)=>(d._OrtBindOutput=oe.Ta)(n,l,f,b),d._OrtClearBoundOutputs=n=>(d._OrtClearBoundOutputs=oe.Ua)(n),d._OrtReleaseBinding=n=>(d._OrtReleaseBinding=oe.Va)(n),d._OrtRunWithBinding=(n,l,f,b,C)=>(d._OrtRunWithBinding=oe.Wa)(n,l,f,b,C),d._OrtRun=(n,l,f,b,C,k,V,F)=>(d._OrtRun=oe.Xa)(n,l,f,b,C,k,V,F),d._OrtEndProfiling=n=>(d._OrtEndProfiling=oe.Ya)(n),d._JsepOutput=(n,l,f)=>(d._JsepOutput=oe.Za)(n,l,f),d._JsepGetNodeName=n=>(d._JsepGetNodeName=oe._a)(n);var pn=d._pthread_self=()=>(pn=d._pthread_self=oe.$a)(),mn=d._malloc=n=>(mn=d._malloc=oe.ab)(n),At=d._free=n=>(At=d._free=oe.bb)(n);d.__emscripten_tls_init=()=>(d.__emscripten_tls_init=oe.cb)();var hi=d.__emscripten_thread_init=(n,l,f,b,C,k)=>(hi=d.__emscripten_thread_init=oe.eb)(n,l,f,b,C,k);d.__emscripten_thread_crashed=()=>(d.__emscripten_thread_crashed=oe.fb)();var gi=(n,l,f,b,C)=>(gi=oe.gb)(n,l,f,b,C),ro=n=>(ro=oe.hb)(n),no=d.__emscripten_thread_exit=n=>(no=d.__emscripten_thread_exit=oe.ib)(n),yi=()=>(yi=oe.jb)(),bi=(n,l)=>(bi=oe.kb)(n,l),fn=n=>(fn=oe.lb)(n),oo=n=>(oo=oe.mb)(n),io=()=>(io=oe.nb)(),wi=d.dynCall_ii=(n,l)=>(wi=d.dynCall_ii=oe.pb)(n,l),vi=n=>(vi=oe.qb)(n),$i=()=>($i=oe.rb)(),_i=n=>(_i=oe.sb)(n),Si=()=>(Si=oe.tb)();d.___start_em_js=839500,d.___stop_em_js=839661;function rl(){var n=oe;n=Object.assign({},n);var l=b=>C=>b(C)>>>0,f=b=>()=>b()>>>0;return n.wa=l(n.wa),n.$a=f(n.$a),n.ab=l(n.ab),n.emscripten_main_runtime_thread_id=f(n.emscripten_main_runtime_thread_id),n.mb=l(n.mb),n.nb=f(n.nb),n}d.wasmMemory=ae,d.stackSave=()=>io(),d.stackRestore=n=>fn(n),d.stackAlloc=n=>oo(n),d.keepRuntimeAlive=()=>0Bi)});var Mi=Wr((gm,cl)=>{cl.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(...e){var a=e.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,a+`\\n`);return}console.error(a)}function threadAlert(...e){var a=e.join(" ");postMessage({cmd:"alert",text:a,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,a)=>{var r=Module.wasmModule;Module.wasmModule=null;var t=new WebAssembly.Instance(r,e);return a(t)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let r=[];self.onmessage=t=>r.push(t),self.startWorker=t=>{Module=t,postMessage({cmd:"loaded"});for(let s of r)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const t of e.data.handlers)Module[t]=(...s)=>{postMessage({cmd:"callHandler",handler:t,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var a=URL.createObjectURL(e.data.urlOrBlob);importScripts(a),URL.revokeObjectURL(a)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(r){if(r!="unwind")throw r}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(r){throw Module.__emscripten_thread_crashed?.(),r}}self.onmessage=handleMessage;\\n\'});var go,Gt,tr,bn,Gr,Hi,yo,ye=Y(()=>{"use strict";go=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},Gt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},tr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],bn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Gr=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Hi=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",yo=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}});var wn=Y(()=>{"use strict"});var Fi=Y(()=>{"use strict";wn()});var qi,ji=Y(()=>{"use strict";qi="1.18.0"});var Ki,pt,bo=Y(()=>{"use strict";ji();Ki="warning",pt={wasm:{},webgl:{},webgpu:{},versions:{common:qi},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Ki=e}},get logLevel(){return Ki}};Object.defineProperty(pt,"logLevel",{enumerable:!0})});var vr,Yi=Y(()=>{"use strict";bo();vr=pt});var Zi=Y(()=>{"use strict"});var Xi=Y(()=>{"use strict";vn()});var Ji=Y(()=>{"use strict"});var ea=Y(()=>{"use strict";vn()});var vn=Y(()=>{"use strict";Zi();Xi();Ji();ea()});var $n=Y(()=>{"use strict";vn()});var wo,ta,rr,Ht,vo=Y(()=>{"use strict";bo();wo=(e,t)=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeStamp(`${e}::ORT::${t}`)},ta=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let i=0;i{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||ta("BEGIN",e)},Ht=e=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||ta("END",e)}});var ra=Y(()=>{"use strict";wn();$n();vo()});var na=Y(()=>{"use strict";ra()});var oa=Y(()=>{"use strict"});var ia=Y(()=>{"use strict"});var aa=Y(()=>{"use strict"});var sa=Y(()=>{"use strict"});var ua=Y(()=>{"use strict";wn();$n()});var da=Y(()=>{"use strict";ua()});var $r=Y(()=>{"use strict";Fi();Yi();na();$n();oa();ia();vo();aa();sa();da()});var _l,Sl,la,ca,pa,xl,Ve,Lt=Y(()=>{"use strict";ye();_l=["V","I","W","E","F"],Sl=(e,t)=>{console.log(`[${_l[e]},${new Date().toISOString()}]${t}`)},pa=(e,t)=>{la=e,ca=t},xl=(e,t)=>{let r=Gr(e),o=Gr(la);r>=o&&Sl(r,typeof t=="function"?t():t)},Ve=(...e)=>{ca&&xl(...e)}});var ma,fa=Y(()=>{"use strict";ye();ma=(e,t)=>new(bn(t))(e)});var _n=Y(()=>{"use strict"});var ha,$o,_o,Cl,Al,ga,xo,So,ba,wa=Y(()=>{"use strict";Lt();_n();ha=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),$o=[],_o=e=>Math.ceil(e/16)*16,Cl=e=>{for(let t=0;t<$o.length;t++){let r=$o[t];if(e<=r)return r}return Math.ceil(e/16)*16},Al=1,ga=()=>Al++,xo=async(e,t,r,o)=>{let i=_o(r),u=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,u,0,i),e.flush(),await u.mapAsync(GPUMapMode.READ);let c=u.getMappedRange();if(o){let p=o();return p.set(new Uint8Array(c,0,r)),p}else return new Uint8Array(c.slice(0,r))}finally{u.destroy()}},So=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[r]of ha)$o.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[])}upload(t,r){let o=r.buffer,i=r.byteOffset,u=r.byteLength,a=_o(u),c=this.storageCache.get(t);if(!c)throw new Error("gpu data for uploading does not exist");if(c.originalSize!==u)throw new Error(`inconsistent data size. gpu data size=${c.originalSize}, data size=${u}`);let p=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=p.getMappedRange();new Uint8Array(h).set(new Uint8Array(o,i,u)),p.unmap();let d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(p,0,c.gpuData.buffer,0,a),Ve("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(p)}memcpy(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(r);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(o.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=_o(o.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(o.gpuData.buffer,0,i.gpuData.buffer,0,u)}registerExternalBuffer(t,r,o){let i;if(o){if(i=this.externalBuffers.get(o),i===void 0)throw new Error("previous buffer is not registered");if(t===o)return Ve("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`);this.externalBuffers.delete(o)}else i=ga();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,i),Ve("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, registered.`),i}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),Ve("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Cl(t),i,u=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||a){let h=(u?this.freeBuffers:this.freeUniformBuffers).get(o);h?h.length>0?i=h.pop():i=this.backend.device.createBuffer({size:o,usage:r}):i=this.backend.device.createBuffer({size:o,usage:r})}else i=this.backend.device.createBuffer({size:o,usage:r});let c={id:ga(),type:0,buffer:i};return this.storageCache.set(c.id,{gpuData:c,originalSize:t}),Ve("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${c.id}`),c}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=this.storageCache.get(t);if(!r)throw new Error("releasing data does not exist");return Ve("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("data does not exist");await xo(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let r=ha.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let o=this.freeBuffers.get(t.size)||[];r===void 0||o.length>=r?t.destroy():o.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let o=this.freeUniformBuffers.get(t.size)||[];r===void 0||o.length>=r?t.destroy():o.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(o=>{o.destroy()}),this.capturedPendingBuffers.delete(t))}},ba=(...e)=>new So(...e)});var Co,ve,Ze=Y(()=>{"use strict";Co=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},ve=e=>new Co(e)});var Ao,It,M,nr,Sn,xn,Cn,Se=Y(()=>{"use strict";Ao=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},It=class{static calcShape(t,r,o=!1){let i=t.length,u=r.length;if(i===0)return r;if(u===0)return t;let a=Math.max(t.length,r.length),c=new Array(a);if(o){if(i<2||u<2)return;let p=Ao.calcMatMulShape([t[i-2],t[i-1]],[r[u-2],r[u-1]]);if(p===void 0)return;[c[a-2],c[a-1]]=p}for(let p=o?3:1;p<=a;p++){let h=i-p<0?1:t[i-p],d=u-p<0?1:r[u-p];if(h!==d&&h>1&&d>1)return;let y=Math.max(h,d);if(h&&d)c[a-p]=Math.max(h,d);else{if(y>1)return;c[a-p]=0}}return c}static isValidBroadcast(t,r){let o=t.length,i=r.length;if(o>i)return!1;for(let u=1;u<=o;u++)if(t[o-u]!==1&&t[o-u]!==r[i-u])return!1;return!0}},M=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let o=t.length;if(o===0)return[];let i=new Array(o),u=o-1;for(;u>=0;){if(t[u]%r===0){i[u]=t[u]/r;break}if(r%t[u]!==0)throw new Error("cannot convert shape");i[u]=1,r/=t[u],u--}for(u--;u>=0;u--)i[u]=t[u];return i}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,o){let i=1;for(let u=r;u=0;--i)o[i]=o[i+1]*t[i+1];return o}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(o=>this.normalizeAxis(o,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(o=>t[o]):t.slice().reverse()}static padShape(t,r){let o=t.length;return t.map((i,u)=>i+r[u]+r[u+o])}static areEqual(t,r){return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}},nr=class e{static adjustPoolAttributes(t,r,o,i,u,a){if(!t&&o.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=o.length?o.push(r[c+2]):o[c]=r[c+2];for(let c=0;c=o[c]||a[c+o.length]>=o[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,o,i,u,a,c){if(c){if(u.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{"use strict";ye();Se();or=64,To=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},De=(e,t=1)=>{let r=To(e,t);return typeof r=="string"?r:r[0]},et=(e,t=1)=>{let r=To(e,t);return typeof r=="string"?r:r[1]},Z=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:M.computeStrides(r)})}),t},Me=e=>e%4===0?4:e%2===0?2:1,$t=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,ir=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,_t=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,fe=(e,t,r,o)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?o==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:o==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Eo=(e,t,r,o,i)=>{let u=typeof r=="number",a=u?r:r.length,c=[...new Array(a).keys()],p=a<2?"u32":a<=4?`vec${a}`:`array`,h=To(t,i),d=typeof h=="string"?h:h[1],y=typeof h=="string"?h:h[0],w={indices:p,value:d,storage:y,tensor:t},_=G=>typeof G=="string"?G:`${G}u`,v={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},S=u?"uniforms.":"",A=`${S}${e}_shape`,I=`${S}${e}_strides`,x="";for(let G=0;G ${w.indices} {\n var indices: ${w.indices};\n var current = offset;\n ${x}\n return indices;\n }`,P=G=>(v.offsetToIndices=!0,a<2?G:`o2i_${e}(${G})`),O=[];if(a>=2)for(let G=a-1;G>=0;G--)O.push(`${fe(I,G,a)} * (indices[${G}])`);let R=a<2?"":`\n fn i2o_${e}(indices: ${w.indices}) -> u32 {\n return ${O.join("+")};\n }`,L=G=>(v.indicesToOffset=!0,a<2?G:`i2o_${e}(${G})`),N=(...G)=>a===0?"0u":`${w.indices}(${G.map(_).join(",")})`,K=(G,ne)=>a<2?`${G}`:`${fe(G,ne,a)}`,Q=(G,ne,xe)=>a<2?`${G}=${xe};`:`${fe(G,ne,a)}=${xe};`,he={},W=(G,ne)=>{v.broadcastedIndicesToOffset=!0;let xe=`${ne.name}broadcastedIndicesTo${e}Offset`;if(xe in he)return`${xe}(${G})`;let Ke=[];for(let Be=a-1;Be>=0;Be--){let Ge=ne.indicesGet("outputIndices",Be+ne.rank-a);Ke.push(`${K(I,Be)} * (${Ge} % ${K(A,Be)})`)}return he[xe]=`fn ${xe}(outputIndices: ${ne.type.indices}) -> u32 {\n return ${Ke.length>0?Ke.join("+"):"0u"};\n }`,`${xe}(${G})`},se=(G,ne)=>(()=>{if(w.storage===w.value)return`${e}[${G}]=${ne};`;if(w.storage==="vec2"&&w.value==="i32")return`${e}[${G}]=vec2(u32(${ne}), select(0u, 0xFFFFFFFFu, ${ne} < 0));`;if(w.storage==="vec2"&&w.value==="u32")return`${e}[${G}]=vec2(u32(${ne}), 0u);`;if(w.storage==="u32"&&w.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ne}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),Ce=G=>(()=>{if(w.storage===w.value)return`${e}[${G}]`;if(w.storage==="vec2"&&w.value==="i32")return`i32(${e}[${G}].x)`;if(w.storage==="vec2"&&w.value==="u32")return`u32(${e}[${G}].x)`;if(w.storage==="u32"&&w.value==="vec4")return`vec4(bool(${e}[${G}] & 0xFFu), bool(${e}[${G}] & 0xFF00u), bool(${e}[${G}] & 0xFF0000u), bool(${e}[${G}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),We=a<2?"":`\n fn get_${e}ByIndices(indices: ${w.indices}) -> ${d} {\n return ${Ce(`i2o_${e}(indices)`)};\n }`,ee=a<2?"":(()=>{let G=c.map(xe=>`d${xe}: u32`).join(", "),ne=c.map(xe=>`d${xe}`).join(", ");return`\n fn get_${e}(${G}) -> ${d} {\n return get_${e}ByIndices(${N(ne)});\n }`})(),ae=(...G)=>{if(G.length!==a)throw new Error(`indices length must be ${a}`);let ne=G.map(_).join(",");return a===0?Ce("0u"):a===1?Ce(ne[0]):(v.get=!0,v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}(${ne})`)},Ae=G=>a<2?Ce(G):(v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}ByIndices(${G})`),me=a<2?"":`\n fn set_${e}ByIndices(indices: ${w.indices}, value: ${d}) {\n ${se(`i2o_${e}(indices)`,"value")}\n }`,ie=a<2?"":(()=>{let G=c.map(xe=>`d${xe}: u32`).join(", "),ne=c.map(xe=>`d${xe}`).join(", ");return`\n fn set_${e}(${G}, value: ${d}) {\n set_${e}ByIndices(${N(ne)}, value);\n }`})();return{impl:()=>{let G=[],ne=!1;return v.offsetToIndices&&(G.push(E),ne=!0),v.indicesToOffset&&(G.push(R),ne=!0),v.broadcastedIndicesToOffset&&(Object.values(he).forEach(xe=>G.push(xe)),ne=!0),v.set&&(G.push(ie),ne=!0),v.setByIndices&&(G.push(me),ne=!0),v.get&&(G.push(ee),ne=!0),v.getByIndices&&(G.push(We),ne=!0),!u&&ne&&G.unshift(`const ${A} = ${w.indices}(${r.join(",")});`,`const ${I} = ${w.indices}(${M.computeStrides(r).join(",")});`),G.join(`\n`)},type:w,offsetToIndices:P,indicesToOffset:L,broadcastedIndicesToOffset:W,indices:N,indicesGet:K,indicesSet:Q,set:(...G)=>{if(G.length!==a+1)throw new Error(`indices length must be ${a}`);let ne=G[a];if(typeof ne!="string")throw new Error("value must be string");let xe=G.slice(0,a).map(_).join(",");return a===0?se("0u",ne):a===1?se(xe[0],ne):(v.set=!0,v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}(${xe}, ${ne})`)},setByOffset:se,setByIndices:(G,ne)=>a<2?se(G,ne):(v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${ne});`),get:ae,getByOffset:Ce,getByIndices:Ae,usage:o,name:e,strides:I,shape:A,rank:a}},U=(e,t,r,o=1)=>Eo(e,t,r,"input",o),j=(e,t,r,o=1)=>Eo(e,t,r,"output",o),An=(e,t,r,o=1)=>Eo(e,t,r,"internal",o),Io=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=or){let r=typeof t=="number"?t:t[0],o=typeof t=="number"?1:t[1],i=typeof t=="number"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||o>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${o}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*o*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${o}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let u=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=u?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,c=u?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r*o*i}u + local_idx;`;return`@compute @workgroup_size(${r}, ${o}, ${i})\n fn main(${a}) {\n ${c}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let o=t.usage==="input"?"read":"read_write",i=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${i}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,o=1){return this.uniforms.push({name:t,type:r,length:o}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:o,length:i}of this.uniforms)if(i&&i>4)o==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(i/8)}>`):t.push(`${r}:array, ${Math.ceil(i/4)}>`);else{let u=i==null||i===1?o:`vec${i}<${o}>`;t.push(`${r}:${u}`)}return`\n struct Uniforms { ${t.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},va=(e,t)=>new Io(e,t),_r=(e,t)=>{let r=e.length,o=[];for(let i=0;i1&&a===1&&o.unshift(u)}return o}});var Il,$a,Tl,El,yt,_a,Sa,Sr=Y(()=>{"use strict";ye();Se();Ze();_e();Il=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},$a=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Tl=(e,t)=>M.sortBasedOnPerm(e,$a(e.length,t)),El=(e,t,r,o)=>{let i=[];i.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let u=0;u{let r=e.dataType,o=e.dims.length,i=$a(o,t),u=Tl(e.dims,i),a=j("output",r,u.length),c=U("a",r,o),p=h=>`\n ${h.registerUniform("output_size","u32").declareVariables(c,a)}\n\n ${El(i,o,c,a)}\n\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${a.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${a.setByOffset("global_idx",c.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:h=>{let d=M.size(u);return{outputs:[{dims:u,dataType:h[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},...Z(h[0].dims,u)]}},getShaderSource:p}},_a=(e,t)=>{Il(e.inputs),e.compute(yt(e.inputs[0],t.perm))},Sa=e=>ve({perm:e.perm})});var Pl,kl,Ol,Rl,Bl,Dl,zl,Ml,Ul,Vl,Tt,xa,Ca,Aa,Ia,Ta,Ea,Pa,ka,Oa,Ra,Ba=Y(()=>{"use strict";ye();Se();_e();In();Sr();Pl={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},kl={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},Ol={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Rl={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Bl=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let u=0;ue[u]);return[r,i]},zl=(e,t)=>{let r=e.length+t.length,o=[],i=0;for(let u=0;u{for(let r=0;r{let r=[];if(!Ml(e,t)){for(let o=0;or.push(o))}return r},Vl=(e,t,r,o,i,u,a)=>{let c=r[0].dims,p=M.size(u),h=M.size(a),d=U("_A",r[0].dataType,c),y=j("output",i,u),w=32,_=`\n var aBestValues : array;\n `;return{name:e,shaderCache:t,getShaderSource:S=>`\n ${S.registerUniform("reduceSize","u32").declareVariables(d,y)}\n ${_}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${S.mainStart(w)}\n\n let outputIndex = global_idx / ${w};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${Ol[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${w}) {\n let candidate = f32(${d.getByOffset("offset + k")});\n bestValue = ${Pl[o]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${w}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${kl[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${y.setByOffset("outputIndex",`${o==="mean"?`${y.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${y.type.storage}(${Rl[o]})`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:u,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},Tt=(e,t,r,o)=>{let i=e.inputs.length===1?r:Po(e.inputs,r),u=i.axes;u.length===0&&!i.noopWithEmptyAxes&&(u=e.inputs[0].dims.map((_,v)=>v));let a=M.normalizeAxes(u,e.inputs[0].dims.length),c=a,p=e.inputs[0],h=Ul(c,e.inputs[0].dims.length);h.length>0&&(p=e.compute(yt(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],c=Bl(c.length,p.dims.length));let[d,y]=Dl(p.dims,c),w=d;i.keepDims&&(w=zl(d,a)),e.compute(Vl(t,{hint:i.cacheKey,inputDependencies:["type"]},[p],o,e.inputs[0].dataType,w,y),{inputs:[p]})},xa=(e,t)=>{Tt(e,"ReduceMeanShared",t,"mean")},Ca=(e,t)=>{Tt(e,"ReduceL1Shared",t,"l1")},Aa=(e,t)=>{Tt(e,"ReduceL2Shared",t,"l2")},Ia=(e,t)=>{Tt(e,"ReduceLogSumExpShared",t,"logSumExp")},Ta=(e,t)=>{Tt(e,"ReduceMaxShared",t,"max")},Ea=(e,t)=>{Tt(e,"ReduceMinShared",t,"min")},Pa=(e,t)=>{Tt(e,"ReduceProdShared",t,"prod")},ka=(e,t)=>{Tt(e,"ReduceSumShared",t,"sum")},Oa=(e,t)=>{Tt(e,"ReduceSumSquareShared",t,"sumSquare")},Ra=(e,t)=>{Tt(e,"ReduceLogSumShared",t,"logSum")}});var Et,Wl,Tn,Po,Pt,Nl,Gl,Hl,Ll,Fl,ql,jl,Kl,Yl,Zl,kt,Da,za,Ma,Ua,Va,Wa,Na,Ga,Ha,La,In=Y(()=>{"use strict";ye();Se();Ze();_e();Ba();Et=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Wl=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Tn=(e,t,r,o,i,u,a=!1,c=!1)=>{let p=[],h=r[0].dims,d=h.length,y=M.normalizeAxes(i,d),w=!c&&y.length===0;h.forEach((A,I)=>{w||y.indexOf(I)>=0?a&&p.push(1):p.push(A)});let _=p.length,v=M.size(p);return{name:e,shaderCache:t,getShaderSource:A=>{let I=[],x=U("_A",r[0].dataType,d),E=j("output",u,_),P=o(x,E,y),O=P[2];for(let R=0,L=0;R=0?(a&&L++,O=`for(var j${R}: u32 = 0; j${R} < ${h[R]}; j${R}++) {\n ${P[2].includes("last_index")?`let last_index = j${R};`:""}\n ${x.indicesSet("input_indices",R,`j${R}`)}\n ${O}\n }`):(I.push(`${x.indicesSet("input_indices",R,E.indicesGet("output_indices",L))};`),L++);return`\n\n ${A.registerUniform("output_size","u32").declareVariables(x,E)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${x.type.indices};\n let output_indices = ${E.offsetToIndices("global_idx")};\n\n ${I.join(`\n`)}\n ${P[0]} // init ops for reduce max/min\n ${P[1]}\n ${O}\n ${P[3]}\n ${P.length===4?E.setByOffset("global_idx","value"):P.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},...Z(h,p)]})}},Po=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),ve({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Pt=(e,t,r,o)=>{let i=e.inputs,u=i.length===1?r:Po(i,r);e.compute(Tn(t,{hint:u.cacheKey,inputDependencies:["rank"]},[i[0]],u.noopWithEmptyAxes&&u.axes.length===0?Wl:o,u.axes,i[0].dataType,u.keepDims,u.noopWithEmptyAxes),{inputs:[0]})},Nl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceLogSum",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Gl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceL1",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},Hl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceL2",t,(o,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ll=(e,t)=>{Et(e.inputs),Pt(e,"ReduceLogSumExp",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},Fl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMax",t,(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(o.indicesSet("input_indices",c,0));return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = max(value, ${o.getByIndices("input_indices")});`,""]})},ql=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMean",t,(o,i,u)=>{let a=1;for(let c=0;c=0||u.length===0)&&(a*=e.inputs[0].dims[c]);return["var sum = f32(0);","",`sum += f32(${o.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${a});`]})},jl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMin",t,(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = min(value, ${o.getByIndices("input_indices")});`,""]})},Kl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceProd",t,(o,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},Yl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceSum",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},Zl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceSumSquare",t,(o,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += t * t;`,""])},kt=(e,t,r)=>{if(t.length===0)return r;let o=1,i=1;for(let u=0;u1024},Da=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ql(e,t):xa(e,t)},za=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gl(e,t):Ca(e,t)},Ma=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hl(e,t):Aa(e,t)},Ua=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ll(e,t):Ia(e,t)},Va=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fl(e,t):Ta(e,t)},Wa=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jl(e,t):Ea(e,t)},Na=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Kl(e,t):Pa(e,t)},Ga=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yl(e,t):ka(e,t)},Ha=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zl(e,t):Oa(e,t)},La=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Nl(e,t):Ra(e,t)}});var Fa,qa,ja,ko,Ka=Y(()=>{"use strict";ye();Ze();In();Fa=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},qa=(e,t)=>{Fa(e.inputs);let r=(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Tn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ja=(e,t)=>{Fa(e.inputs);let r=(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Tn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ko=e=>ve(e)});var Xl,Ql,Jl,En,Ya,Za,Oo=Y(()=>{"use strict";ye();Se();Ze();_e();Xl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,o=e[r],i=o.dataType,u=o.dims.length;e.forEach((a,c)=>{if(c!==r){if(a.dataType!==i)throw new Error("input tensors should be one type");if(a.dims.length!==u)throw new Error("input tensors should have the same shape");a.dims.forEach((p,h)=>{if(h!==t&&p!==o.dims[h])throw new Error("non concat dimensions must match")})}})},Ql=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,Jl=(e,t)=>{let r=e.length,o=[];for(let i=0;i{let i=M.size(r),u=new Array(e.length),a=new Array(e.length),c=0,p=[],h=[],d=[{type:12,data:i}];for(let S=0;S`uniforms.sizeInConcatAxis${S}`).join(","),v=S=>`\n\n ${(()=>{S.registerUniform("outputSize","u32");for(let A=0;A(${_});\n ${w} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Jl(a,y)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:o}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d}),getShaderSource:v}},Ya=(e,t)=>{let r=e.inputs,o=r[0].dims,i=M.normalizeAxis(t.axis,o.length);Xl(r,i);let u=o.slice();u[i]=r.reduce((c,p)=>c+(p.dims.length>i?p.dims[i]:0),0);let a=r.filter(c=>M.size(c.dims)>0);e.compute(En(a,i,u,r[0].dataType),{inputs:a})},Za=e=>ve({axis:e.axis})});var ec,tc,rc,nc,Pn,oc,Xa,Ro=Y(()=>{"use strict";ye();_n();_e();Oo();ec=(e,t)=>{let r=e[0],o=e[1],i=e[2],u=e[3],a=e[4],c=e[5];if(a&&c)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error(\'Input "input" must have 3 dimensions\');let p=r.dims[0],h=r.dims[1],d=r.dims[2];if(i.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimensions\');if(o.dims.length!==2)throw new Error(\'Input "weights" is expected to have 2 dimensions\');if(o.dims[0]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==o.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let y=i.dims[0]/3,w=y,_=w;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let E of t.qkvHiddenSizes)if(E%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");y=t.qkvHiddenSizes[0],w=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let v=h;if(y!==w)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==y+w+_)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let S=0;if(a){if(w!==_)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(a.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(a.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(a.dims[1]!==p)throw new Error(\'Input "past" second dimension must be batch_size\');if(a.dims[2]!==t.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(a.dims[4]!==w/t.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');t.pastPresentShareBuffer||(S=a.dims[3])}let A=v+S,I=-1,x=0;if(u)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");return{batchSize:p,sequenceLength:h,pastSequenceLength:S,kvSequenceLength:v,totalSequenceLength:A,maxSequenceLength:I,inputHiddenSize:d,hiddenSize:y,vHiddenSize:_,headSize:Math.floor(y/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},tc=(e,t,r,o)=>{let i=Me(o),u=64,a=o/i;a{let _=j("x",t.dataType,t.dims,i),S=[{name:"d_inv",type:et(t.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${w.registerUniforms(S).declareVariables(_)}\n ${w.mainStart([u,1,1])}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = workgroup_id.x * uniforms.d_comp + local_offset;\n\n var thread_max_vector = ${d}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n thread_max_vector = max(${d}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(i){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${i}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${u}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${d}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n sum_vector += exp(${d}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(i){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${i}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${u}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n x[offset + i] = ${_.type.value}(uniforms.d_inv);\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n var f32input = ${d}(x[offset + i]);\n x[offset + i] = ${_.type.value}(exp(f32input - max_value) / sum);\n }\n }\n }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${h};${i}`},getShaderSource:y,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:p})}},rc=(e,t,r,o,i,u,a)=>{let c=a+i.kvSequenceLength,p=[i.batchSize,i.numHeads,i.sequenceLength,c],h=u.scale===0?1/Math.sqrt(i.headSize):u.scale,d=Me(i.headSize),y=i.headSize/d,w=12,_={x:Math.ceil(c/w),y:Math.ceil(i.sequenceLength/w),z:i.batchSize*i.numHeads},v=[{type:12,data:i.sequenceLength},{type:12,data:y},{type:12,data:c},{type:12,data:i.numHeads},{type:1,data:h}],S=o?["type","type","type"]:["type","type"],A=I=>{let x=U("q",t.dataType,t.dims,d),E=U("key",r.dataType,r.dims,d),P=[x,E];o&&P.push(U("relative_position_bias",o.dataType,o.dims));let O=j("output",t.dataType,p),R=et(1,d),L=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return`\n const TILE_SIZE = ${w}u;\n\n var tileQ: array<${x.type.storage}, ${w*w}>;\n var tileK: array<${x.type.storage}, ${w*w}>;\n ${I.registerUniforms(L).declareVariables(...P,O)}\n ${I.mainStart([w,w,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${R}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${R}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n let headOffset = headIdx * uniforms.M * uniforms.N;\n if (global_id.y < uniforms.M && global_id.x < uniforms.N) {\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(d){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${d}`)}})()};\n output[outputIdx] = ${O.type.value} (sum * uniforms.alpha) + ${o?"relative_position_bias[outputIdx]":"0.0"};\n }\n }`};return{name:"AttentionProbs",shaderCache:{hint:`${d}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:p,dataType:t.dataType,gpuDataType:0}],dispatchGroup:_,programUniforms:v}),getShaderSource:A}},nc=(e,t,r,o,i)=>{let u=i+o.kvSequenceLength,a=[o.batchSize,o.sequenceLength,o.vHiddenSize],c=12,p={x:Math.ceil(o.vHeadSize/c),y:Math.ceil(o.sequenceLength/c),z:o.batchSize*o.numHeads},h=[{type:12,data:o.sequenceLength},{type:12,data:u},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType,gpuDataType:0}],dispatchGroup:p,programUniforms:h}),getShaderSource:w=>{let _=U("probs",t.dataType,t.dims),v=U("v",r.dataType,r.dims),S=j("output",t.dataType,a),A=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return`\n const TILE_SIZE = ${c}u;\n var tileQ: array<${_.type.value}, ${c*c}>;\n var tileK: array<${_.type.value}, ${c*c}>;\n ${w.registerUniforms(A).declareVariables(_,v,S)}\n ${w.mainStart([c,c,1])}\n let headIdx = workgroup_id.z;\n let m = global_id.y;\n let n = global_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${_.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads;\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + currentBatchHeadNumber * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`}}},Pn=(e,t,r,o,i,u,a,c,p,h,d)=>{let y=e.outputCount>1,w=e.outputCount>2,_=y&&w?h.pastSequenceLength:0,v=_+h.kvSequenceLength,S=[h.batchSize,h.numHeads,v,h.headSize],A=a?[a,r]:[r],I=y?e.compute(En(A,2,S,r.dataType),{inputs:A,outputs:[1]})[0]:r,x=[h.batchSize,h.numHeads,v,h.headSize],E=c?[c,o]:[o],P=w?e.compute(En(E,2,x,o.dataType),{inputs:E,outputs:[2]})[0]:o,O=[t,I];p&&O.push(p);let R=e.compute(rc(e,t,I,p,h,d,_),{inputs:O,outputs:[-1]})[0];e.compute(tc(e,R,h.batchSize*h.numHeads*h.sequenceLength,v),{inputs:[R],outputs:[]});let L=[R,P];e.compute(nc(e,R,P,h,_),{inputs:L,outputs:[0]})},oc=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],o=t.sequenceLength,i=t.inputHiddenSize,u=t.headSize,a=12,c={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:o},{type:12,data:i},{type:12,data:u},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],d=y=>{let w=j("output_q",p[0].dataType,r),_=j("output_k",p[0].dataType,r),v=j("output_v",p[0].dataType,r),S=U("input",p[0].dataType,p[0].dims),A=U("weight",p[1].dataType,p[1].dims),I=U("bias",p[2].dataType,p[2].dims),x=S.type.storage,E=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`\n const TILE_SIZE = ${a}u;\n var tileInput: array<${x}, ${a*a}>;\n var tileWeightQ: array<${x}, ${a*a}>;\n var tileWeightK: array<${x}, ${a*a}>;\n var tileWeightV: array<${x}, ${a*a}>;\n ${y.registerUniforms(E).declareVariables(S,A,I,w,_,v)}\n ${y.mainStart([a,a,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${x}(0);\n var valueK = ${x}(0);\n var valueV = ${x}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:h}),getShaderSource:d},{inputs:p,outputs:[-1,-1,-1]})},Xa=(e,t)=>{let r=ec(e.inputs,t),[o,i,u]=oc(e,r);return Pn(e,o,i,u,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var ic,ac,sc,Qa,Ja=Y(()=>{"use strict";$r();ye();Se();Ze();_e();ic=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(o,i,u)=>{let a=i.length;if(a!==o.length)throw new Error(`${u}: num dimensions != ${a}`);i.forEach((c,p)=>{if(c!==o[p])throw new Error(`${u}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let o=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,o,"Invalid input scale"),r(e[2].dims,o,"Invalid input B"),r(e[3].dims,o,"Invalid input mean"),r(e[4].dims,o,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},ac=(e,t)=>{let{epsilon:r,spatial:o,format:i}=t,u=e[0].dims,a=o?Me(u[u.length-1]):1,c=i==="NHWC"&&u.length>1?a:1,p=M.size(u)/a,h=o,d=h?u.length:u,y=U("x",e[0].dataType,e[0].dims,a),w=U("scale",e[1].dataType,e[1].dims,c),_=U("bias",e[2].dataType,e[2].dims,c),v=U("inputMean",e[3].dataType,e[3].dims,c),S=U("inputVar",e[4].dataType,e[4].dims,c),A=j("y",e[0].dataType,d,a),I=()=>{let E="";if(o)E=`let cOffset = ${u.length===1?"0u":i==="NHWC"?`outputIndices[${u.length-1}] / ${a}`:"outputIndices[1]"};`;else if(i==="NCHW")E=`\n ${A.indicesSet("outputIndices","0","0")}\n let cOffset = ${A.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${w.type.indices}(0);\n cIndices[0] = outputIndices[${u.length-1}];`;for(let P=1;P`\n const epsilon = ${r};\n ${E.registerUniform("outputSize","u32").declareVariables(y,w,_,v,S,A)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${A.offsetToIndices(`global_idx * ${a}`)};\n ${I()}\n let scale = ${w.getByOffset("cOffset")};\n let bias = ${_.getByOffset("cOffset")};\n let inputMean = ${v.getByOffset("cOffset")};\n let inputVar = ${S.getByOffset("cOffset")};\n let x = ${y.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${A.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${o}_${a}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...Z(u)]:[{type:12,data:p}]})}},sc=e=>ve(e),Qa=(e,t)=>{let{inputs:r,outputCount:o}=e,i=sc({...t,outputCount:o});if(vr.webgpu.validateInputContent&&ic(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ac(r,i))}});var uc,dc,es,ts=Y(()=>{"use strict";Se();_e();uc=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},dc=e=>{let t=e[0].dims,r=e[0].dims[2],o=M.size(t)/4,i=e[0].dataType,u=U("input",i,t,4),a=U("bias",i,[r],4),c=U("residual",i,t,4),p=j("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:d=>`\n const channels = ${r}u / 4;\n ${d.declareVariables(u,a,c,p)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes(o)}\n let value = ${u.getByOffset("global_idx")}\n + ${a.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")};\n ${p.setByOffset("global_idx","value")}\n }`}},es=e=>{uc(e.inputs),e.compute(dc(e.inputs))}});var lc,ke,rs,ns,os,is,as,ss,us,ds,ls,cc,cs,ps,ms,fs,kn,hs,On,gs,ys,bs,ws,vs,$s,_s,Ss,xs,Cs,As,Is,Ts,Es,Ps,ks,Os,Rs,Bo,Do,Bs,Ds,zs,Rn=Y(()=>{"use strict";ye();Se();Ze();_e();lc=(e,t,r,o,i,u)=>{let a=Math.ceil(t/4),c="";typeof i=="string"?c=`${i}(a)`:c=i("a");let p=U("inputData",r,[a],4),h=j("outputData",o,[a],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(p,h)}\n\n ${u??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${p.getByOffset("global_idx")};\n ${h.setByOffset("global_idx",c)}\n }`},ke=(e,t,r,o,i,u=e.dataType)=>({name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:a=>lc(a,M.size(e.dims),e.dataType,u,r,o),getRunData:a=>({outputs:[{dims:e.dims,dataType:u}],dispatchGroup:{x:Math.ceil(M.size(a[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(M.size(e.dims)/4)}]})}),rs=e=>{e.compute(ke(e.inputs[0],"Abs","abs"))},ns=e=>{e.compute(ke(e.inputs[0],"Acos","acos"))},os=e=>{e.compute(ke(e.inputs[0],"Acosh","acosh"))},is=e=>{e.compute(ke(e.inputs[0],"Asin","asin"))},as=e=>{e.compute(ke(e.inputs[0],"Asinh","asinh"))},ss=e=>{e.compute(ke(e.inputs[0],"Atan","atan"))},us=e=>{e.compute(ke(e.inputs[0],"Atanh","atanh"))},ds=e=>ve(e),ls=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute \'to\' from \'Cast\' operator): ${t.to}`)}e.compute(ke(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},cc=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:xn,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:Cn;return ve({min:t,max:r})},cs=(e,t)=>{let r=e.inputs.length===1?t:cc(e.inputs),o=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Clip",i=>`clamp(${i}, clip_min_, clip_max_)`,`\n const clip_min_: vec4<${o}> = vec4(${o}(${r.min}));\n const clip_max_: vec4<${o}> = vec4(${o}(${r.max}));\n`,r.cacheKey),{inputs:[0]})},ps=e=>{e.compute(ke(e.inputs[0],"Ceil","ceil"))},ms=e=>{e.compute(ke(e.inputs[0],"Cos","cos"))},fs=e=>{e.compute(ke(e.inputs[0],"Cosh","cosh"))},kn=e=>ve(e),hs=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Elu",o=>`elu_vf32(${o})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},On=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,gs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,On(t)))},ys=e=>{e.compute(ke(e.inputs[0],"Exp","exp"))},bs=e=>{e.compute(ke(e.inputs[0],"Floor","floor"))},ws=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,On(t)))},vs=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"LeakyRelu",o=>`select(leaky_relu_alpha_ * ${o}, ${o}, ${o} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},$s=e=>{e.compute(ke(e.inputs[0],"Not",t=>`!${t}`))},_s=e=>{e.compute(ke(e.inputs[0],"Neg",t=>`-${t}`))},Ss=e=>{e.compute(ke(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},xs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Cs=e=>{e.compute(ke(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},As=e=>ve(e),Is=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"HardSigmoid",o=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${o} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Ts=e=>{e.compute(ke(e.inputs[0],"Sin","sin"))},Es=e=>{e.compute(ke(e.inputs[0],"Sinh","sinh"))},Ps=e=>{e.compute(ke(e.inputs[0],"Sqrt","sqrt"))},ks=e=>{e.compute(ke(e.inputs[0],"Tan","tan"))},Os=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Rs=e=>{e.compute(ke(e.inputs[0],"Tanh",Os))},Bo=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Os("v")};\n}\n`,Do=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Bs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"FastGelu",Do,Bo(t),void 0,e.inputs[0].dataType))},Ds=(e,t)=>{let r=et(e.inputs[0].dataType);return e.compute(ke(e.inputs[0],"ThresholdedRelu",o=>`select(vec4<${r}>(0.0), ${o}, ${o} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},zs=e=>{e.compute(ke(e.inputs[0],"Log","log"))}});var pc,mc,Us,Vs=Y(()=>{"use strict";Se();_e();Rn();pc=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},mc=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=U("input",e[0].dataType,e[0].dims,4),o=U("bias",e[0].dataType,[e[0].dims[2]],4),i=j("output",e[0].dataType,t,4),u=M.size(t)/4,a=De(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:p=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${p.declareVariables(r,o,i)}\n\n ${On(a)}\n\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes(u)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${i.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},Us=e=>{pc(e.inputs),e.compute(mc(e.inputs))}});var fc,hc,Ot,Ws,Ns,Gs,Hs,Ls,Fs,qs,js,Ks,Ys,Zs=Y(()=>{"use strict";ye();Se();_e();fc=(e,t,r,o,i,u,a,c,p,h,d,y)=>{let w,_;typeof c=="string"?w=_=(x,E)=>`${c}((${x}),(${E}))`:typeof c=="function"?w=_=c:(w=c.scalar,_=c.vector);let v=j("outputData",d,o.length,4),S=U("aData",p,t.length,4),A=U("bData",h,r.length,4),I;if(i)if(u){let x=M.size(t)===1,E=M.size(r)===1,P=t.length>0&&t[t.length-1]%4===0,O=r.length>0&&r[r.length-1]%4===0;x||E?I=v.setByOffset("global_idx",_(x?`${S.type.value}(${S.getByOffset("0")}.x)`:S.getByOffset("global_idx"),E?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):I=`\n let outputIndices = ${v.offsetToIndices("global_idx * 4u")};\n let offsetA = ${S.broadcastedIndicesToOffset("outputIndices",v)};\n let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",v)};\n ${v.setByOffset("global_idx",_(a||P?S.getByOffset("offsetA / 4u"):`${S.type.value}(${S.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||O?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else I=v.setByOffset("global_idx",_(S.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!u)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let x=(E,P,O="")=>{let R=`aData[indexA${P}][componentA${P}]`,L=`bData[indexB${P}][componentB${P}]`;return`\n let outputIndices${P} = ${v.offsetToIndices(`global_idx * 4u + ${P}u`)};\n let offsetA${P} = ${S.broadcastedIndicesToOffset(`outputIndices${P}`,v)};\n let offsetB${P} = ${A.broadcastedIndicesToOffset(`outputIndices${P}`,v)};\n let indexA${P} = offsetA${P} / 4u;\n let indexB${P} = offsetB${P} / 4u;\n let componentA${P} = offsetA${P} % 4u;\n let componentB${P} = offsetB${P} % 4u;\n ${E}[${P}] = ${O}(${w(R,L)});\n `};d===9?I=`\n var data = vec4(0);\n ${x("data",0,"u32")}\n ${x("data",1,"u32")}\n ${x("data",2,"u32")}\n ${x("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:I=`\n ${x("outputData[global_idx]",0)}\n ${x("outputData[global_idx]",1)}\n ${x("outputData[global_idx]",2)}\n ${x("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(S,A,v)}\n\n ${y??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${I}\n }`},hc=(e,t,r,o,i,u,a=r.dataType)=>{let c=!M.areEqual(r.dims,o.dims),p=r.dims,h=M.size(r.dims),d=!1,y=!1,w=[c];if(c){let _=It.calcShape(r.dims,o.dims,!1);if(!_)throw new Error("Can\'t perform binary op on the given tensors");p=_,h=M.size(p);let v=M.size(r.dims)===1,S=M.size(o.dims)===1,A=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,I=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;w.push(v),w.push(S),w.push(A),w.push(I);let x=1;for(let E=1;E_.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:_=>fc(_,r.dims,o.dims,p,d,c,y,i,r.dataType,o.dataType,a,u),getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(M.size(p)/4)},...Z(r.dims,o.dims,p)]})}},Ot=(e,t,r,o,i,u)=>{e.compute(hc(t,i??"",e.inputs[0],e.inputs[1],r,o,u))},Ws=e=>{Ot(e,"Add",(t,r)=>`${t}+${r}`)},Ns=e=>{Ot(e,"Div",(t,r)=>`${t}/${r}`)},Gs=e=>{Ot(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Hs=e=>{Ot(e,"Mul",(t,r)=>`${t}*${r}`)},Ls=e=>{let t=U("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ot(e,"Pow",{scalar:(o,i)=>`pow_custom(${o},${i})`,vector:(o,i)=>`pow_vector_custom(${o},${i})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Fs=e=>{Ot(e,"Sub",(t,r)=>`${t}-${r}`)},qs=e=>{Ot(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},js=e=>{Ot(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Ks=e=>{Ot(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Ys=e=>{Ot(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var St,xt,Ct,Bn,Ft=Y(()=>{"use strict";ye();Se();St=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},xt=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},Ct=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},Bn=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,o]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:o}}else if(t==="Clip"){let[r,o]=e?.activation_params||[xn,Cn];return{activation:t,clipMax:o,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var tt,Dn,zn=Y(()=>{"use strict";tt=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Dn=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var Mn,zo=Y(()=>{"use strict";Mn=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var yc,bc,Hr,Xs,wc,Lr,vc,Un,Fr=Y(()=>{"use strict";ye();Se();_e();Ft();zn();yc=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,bc=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,Hr=(e,t,r="f32",o,i=!1,u=32,a=!1,c=32)=>{let p=t[1]*e[1],h=t[0]*e[0],d=i?p:u,y=i?u:p,w=d/t[0],_=u/t[1];if(!((i&&w===4&&e[1]===4||!i&&(w===3||w===4))&&d%t[0]===0&&u%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${w} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${w} must be 3 or 4.\n tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}. tileInner ${u} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${d/w}>, ${y}>;\nvar mm_Bsub: array, ${h/e[0]}>, ${u}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${w};\nconst tileInner = ${u};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${a?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${p};\n\n let num_tiles = ${a?`${Math.ceil(c/u)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${c}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${_};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${yc(i,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${o?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${w===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${bc(i,w)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Xs=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,wc=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Lr=(e,t,r="f32",o,i=!1,u=32,a=!1,c=32,p=!1)=>{let h=e[1]*t[1],d=e[0]*t[0],y=i?h:u,w=i?u:h;if(!(w%t[1]===0&&y%t[0]===0&&u%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${y} must be divisible by workgroupSize[0]${t[0]}, tileInner ${u} must be divisible by workgroupSize[1]${t[1]}`);let _=w/t[1],v=y/t[0],S=u/t[1],A=p?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${h};\n let globalColStart = i32(workgroupId.x) * ${d};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${w}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${y}; inputCol = inputCol + ${t[0]}) {\n ${Xs(i,o)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${h};\n\nlet tileRowA = i32(localId.y) * ${_};\nlet tileColA = i32(localId.x) * ${v};\nlet tileRowB = i32(localId.y) * ${S};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${v}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Xs(i,o)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${S}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${wc(i)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${w}>;\n var mm_Bsub : array, ${u}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${u};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${a?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${a?`${Math.ceil(c/u)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${c}`:"0"};\n\n var acc : array, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${A}\n }\n`},vc=(e,t,r,o,i,u=!1)=>{let[a,c,p]=i,[h,d,y,w]=o,_=_r(a,p),v=_r(c,p),S=De(o[0].type.tensor),A=()=>{let E=d.rank,P=h.rank,O=`var aIndices: ${d.type.indices};`;for(let R=E-2-1,L=P-1;R>=0;R--,L--)O+=`\naIndices[${R}] = ${P>1?`batchIndices[${L}]`:"batchIndices"};`;return _.forEach(R=>{O+=`\naIndices[${R}] = 0;`}),O+=`\naIndices[${E-2}] = u32(row);\n aIndices[${E-1}] = u32(colIn);`,O},I=()=>{let E=y.rank,P=h.rank,O=`var bIndices: ${y.type.indices};`;for(let R=E-2-1,L=P-1;R>=0;R--,L--)O+=`\nbIndices[${R}] = ${P>1?`batchIndices[${L}]`:"batchIndices"};`;return v.forEach(R=>{O+=`\nbIndices[${R}] = 0;`}),O+=`\nbIndices[${E-2}] = u32(row);\n bIndices[${E-1}] = u32(colIn);`,O};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${tt(e,S)} {\n var value = ${tt(e,S)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n ${A()}\n value = ${d.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${tt(e,S)} {\n var value = ${tt(e,S)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n ${I()}\n value = ${y.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${tt(e,S)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${u?"bias[colIn]":`${tt(e,S)}(bias[row])`};`:""}\n ${r}\n ${w.setByIndices("vec3(coords)","value")}\n }\n }\n `},Un=(e,t,r,o,i=!1)=>{let u=e[0].dims,a=e[1].dims,c=u.slice(0,-2),p=a.slice(0,-2),h=o?o.slice(0,-2):r.slice(0,-2),d=M.size(h),y=u[u.length-2],w=u[u.length-1],_=a[a.length-1],v=w%4===0&&_%4===0,S=y<=8?[4,1,1]:[4,4,1],A=[8,8,1],I=[Math.ceil(_/A[0]/S[0]),Math.ceil(y/A[1]/S[1]),Math.ceil(d/A[2]/S[2])],x=v?4:1,E=[...c,y,w/x],P=E.length,O=[...p,w,_/x],R=O.length,L=[d,y,_/x],N=[{type:6,data:y},{type:6,data:_},{type:6,data:w}];xt(t,N),N.push(...Z(h,E,O));let K=["rank","rank"],Q=e.length>2;Q&&(N.push(...Z(e[2].dims)),K.push("rank")),N.push(...Z(L));let he=W=>{let se=h.length,Ce=An("batchDims",e[0].dataType,se,1),We=De(e[0].dataType),ee=U("a",e[0].dataType,P,x),ae=U("b",e[1].dataType,R,x),Ae=j("result",e[0].dataType,L.length,x),me=[ee,ae];if(Q){let G=i?x:1;me.push(U("bias",e[2].dataType,e[2].dims.length,G))}let ie=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ct(t,ie);let ue=De(Ae.type.tensor),le=St(t,Ae.type.value,ue),qe=vc(x,Q,le,[Ce,ee,ae,Ae],[c,p,h],i);return`\n ${W.registerUniforms(ie).registerInternalVariables(Ce).declareVariables(...me,Ae)}\n ${qe}\n ${v?Hr(S,A,We,Ce):Lr(S,A,We,Ce)}\n `};return{name:"MatMul",shaderCache:{hint:`${S};${t.activation};${v};${i}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:I[0],y:I[1],z:I[2]},programUniforms:N}),getShaderSource:he}}});var $c,Qs,Js=Y(()=>{"use strict";ye();Lt();_e();Ft();zn();zo();Fr();$c=(e,t,r,o,i=!1,u,a=4,c=4,p=4,h="f32")=>{let d=Q=>{switch(Q){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Q} is not supported.`)}},y=Q=>{switch(Q){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Q} is not supported.`)}},w=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,_=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,v=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",S=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",I=e?"col":"row",x=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${A} / outWidth;\n let outCol = ${A} % outWidth;\n\n let WRow = ${I} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${I} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${I} % inChannels;\n var resData = ${tt(a,h)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the \'same\' padding type.\n if (xRow >= 0 && xRow < ${v} && xCol >= 0 && xCol < ${S}) {\n ${w}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${d(a)}\n }\n return resData;`,E=e?t&&o?`\n let col = colIn * ${a};\n ${x}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${x}\n }\n return ${tt(a,h)}(0.0);`:o&&r?`\n let col = colIn * ${a};\n ${x}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${x}\n }\n return ${tt(a,h)}(0.0);`,P=`${y(c)}`,O=tt(p,h),R=e?tt(a,h):tt(c,h),L=e?tt(c,h):tt(a,h),N=St(u,O,h);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${R} {\n ${e?E:P}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${L} {\n ${e?P:E}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${O}) {\n let col = colIn * ${p};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${_}\n ${Dn(i)}\n ${N}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Qs=(e,t,r,o,i,u,a,c)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],d=r[0],y=p?r[2]:r[3],w=p?r[1]:r[2],_=p?r[3]:r[1],v=p&&(h%4===0||h%3===0)&&_%4===0,S=p?_:y*w,A=p?y*w:_,I=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(S/I[0]/x[0]),Math.ceil(A/I[1]/x[1]),Math.ceil(d/I[2]/x[2])];Ve("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let P=v?p&&h%4!==0?3:4:1,O=I[1]*x[1],R=I[0]*x[0],L=Math.max(I[0]*P,I[1]),N=o%O===0,K=i%R===0,Q=u%L===0,he=v?[P,4,4]:[1,1,1],W=[{type:6,data:o},{type:6,data:i},{type:6,data:u},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];xt(t,W),W.push(...Z(e[0].dims,e[1].dims));let se=["rank","rank"];a&&(W.push(...Z(e[2].dims)),se.push("rank")),W.push(...Z(r));let Ce=We=>{let ee=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Ct(t,ee);let ae=v?4:1,Ae=De(e[0].dataType),me=`\n fn setOutputAtIndex(flatIndex : i32, value : ${v?`vec4<${Ae}>`:Ae}) {\n result[flatIndex] = ${v?`vec4<${Ae}>`:Ae}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${v?`vec4<${Ae}>`:Ae}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${v?"/ 4":""}, value);\n }`,ie=U("x",e[0].dataType,e[0].dims.length,P===3?1:P),ue=U("w",e[1].dataType,e[1].dims.length,ae),le=[ie,ue],qe=j("result",e[0].dataType,r.length,ae);if(a){let G=U("bias",e[2].dataType,e[2].dims.length,ae);le.push(G),me+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${v?`vec4<${Ae}>`:Ae} {\n return bias[coords.${p?"w":"y"}${v?"/ 4":""}];\n }`}return`\n ${Mn("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${We.registerUniforms(ee).declareVariables(...le,qe)}\n ${me}\n ${$c(p,N,K,Q,a,t,he[0],he[1],he[2],Ae)}\n ${v?Hr(x,I,Ae,void 0,!p,L):Lr(x,I,Ae,void 0,!p,L,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${P};${v};${N};${K};${Q};${O};${R};${L}`,inputDependencies:se},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:W}),getShaderSource:Ce}}});var Mo,eu,tu=Y(()=>{"use strict";ye();Se();_e();Uo();Ft();Mo=(e,t,r)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",u=e[0].dims,a=e[1].dims,c=a[0]/t.group,p=t.format==="NHWC",h=Vn(u,a,t.dilations,t.pads,t.strides,p),d=M.size(h),y=[{type:12,data:d},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:c}];xt(t,y),y.push(...Z(u,a));let w=["rank","rank"];o&&(y.push(...Z(e[2].dims)),w.push("rank")),y.push(...Z(h));let _=v=>{let S=j("output",e[0].dataType,h.length),A=De(S.type.tensor),I=St(t,S.type.value,A),x=U("x",e[0].dataType,u.length),E=U("w",e[1].dataType,a.length),P=[x,E];o&&P.push(U("b",e[2].dataType,e[2].dims.length));let O=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Ct(t,O),`\n ${v.registerUniforms(O).declareVariables(...P,S)}\n\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${S.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${p?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel / uniforms.output_channels_per_group;\n\n var value: ${S.type.value} = ${S.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = group_id * uniforms.w_shape[1] + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[${p?1:2}]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[${p?2:3}]) {\n continue;\n }\n\n let xVal = ${p?x.get("batch","xHeight","xWidth","input_channel"):x.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${E.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${i}\n ${I}\n ${S.setByOffset("global_idx","value")}\n }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:w},getRunData:()=>({outputs:[{dims:r?r(h):h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:y}),getShaderSource:_}},eu=(e,t,r)=>{let o=e.length>2,i=Me(r[3]),u=Me(r[2]),a=M.size(r)/i/u,c=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],h=[r[0],r[1],r[2],r[3]/i],d=[{type:12,data:a},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];xt(t,d),d.push(...Z(c,p,h));let y=(u-1)*t.strides[1]+p[1],w=_=>{let v=j("output",e[0].dataType,h.length,i),S=De(v.type.tensor),A=St(t,v.type.value,S),I=U("x",e[0].dataType,c.length,i),x=U("w",e[1].dataType,p.length,i),E=[I,x];o&&E.push(U("b",e[2].dataType,e[2].dims,i));let P=o?"value += b[output_channel];":"",O=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ct(t,O),`\n ${_.registerUniforms(O).declareVariables(...E,v)}\n ${_.mainStart()}\n ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${u}u;\n let col = (index1 % width1) * ${u}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${I.type.value}, ${y}>;\n var values: array<${v.type.value}, ${u}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w\'s height/width.\n for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${y}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${I.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${I.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) {\n let w_val = ${x.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${u}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${u}u; i++) {\n var value = values[i];\n ${P}\n ${A}\n ${v.set("batch","row","col + i","output_channel","value")};\n }\n }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${u};${y};${p[0]};${p[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:w}}});var Vo,_c,ru,Wo=Y(()=>{"use strict";ye();Se();Fr();_e();Ft();Vo=(e,t,r,o,i=!1)=>{let u=e[0].dims,a=e[1].dims,c=u[u.length-2],p=a[a.length-1],h=u[u.length-1],d=Me(p),y=Me(h),w=Me(c),_=M.size(r)/d/w,v=e.length>2,S=o?o.slice(0,-2):r.slice(0,-2),I=[M.size(S),c,p],x=[{type:12,data:_},{type:12,data:c},{type:12,data:p},{type:12,data:h}];xt(t,x),x.push(...Z(S,u,a)),v&&x.push(...Z(e[2].dims)),x.push(...Z(I));let E=P=>{let O=An("batch_dims",e[0].dataType,S.length),R=U("a",e[0].dataType,u.length,y),L=U("b",e[1].dataType,a.length,d),N=j("output",e[0].dataType,I.length,d),K=De(N.type.tensor),Q=St(t,N.type.value,K),he=[R,L],W="";if(v){let ie=i?d:1;he.push(U("bias",e[2].dataType,e[2].dims.length,ie)),W=`${i?`value += bias[col / ${ie}];`:`value += ${N.type.value}(bias[row + i]);`}`}let se=u.slice(0,-2),Ce=a.slice(0,-2),We=_r(se,S),ee=_r(Ce,S),ae=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ct(t,ae);let Ae=(ie,ue)=>{let le=ie.rank,qe=ie.name;if(le===2)return`var ${qe}_indices = ${ie.type.indices}(0u, 0u);`;let G=O.rank,ne=`var ${qe}_indices: ${ie.type.indices};`;for(let xe=le-2-1,Ke=G-1;xe>=0;xe--,Ke--)ne+=`\n${qe}_indices[${xe}] = ${G>1?`batch_indices[${Ke}]`:"batch_indices"};`;return ue.forEach(xe=>{ne+=`\n${qe}_indices[${xe}] = 0;`}),ne+=`${qe}_indices[${le-2}] = 0u;\n ${qe}_indices[${le-1}] = 0u;`,ne},me=()=>{let ie=`var a_data: ${R.type.value};`;for(let ue=0;ue;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) {\n ${me()}\n }\n for (var i = 0u; i < ${w}u; i++) {\n var value = values[i];\n ${W}\n ${Q}\n let cur_indices = ${N.type.indices}(batch, row + i, col);\n let offset = ${N.indicesToOffset("cur_indices")};\n ${N.setByOffset(`offset / ${d}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${d};${y};${w};${i}`,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:x}),getShaderSource:E}},_c=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},ru=e=>{_c(e.inputs);let t=It.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can\'t use matmul on the given tensors");let r=t[t.length-1],o=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&o<8?e.compute(Vo(e.inputs,{activation:""},t)):e.compute(Un(e.inputs,{activation:""},t))}});var Vn,No,Sc,nu,Go,xc,Cc,Ho,Uo=Y(()=>{"use strict";Se();Js();Fr();tu();Ft();Wo();Sr();Vn=(e,t,r,o,i,u)=>{let a=e[0],c=e.slice(u?1:2,u?3:4),p=c.length,h=t[0],y=t.slice(2).map((v,S)=>v+(v-1)*(r[S]-1)),_=c.map((v,S)=>v+o[S]+o[S+p]).map((v,S)=>Math.floor((v-y[S]+i[S])/i[S]));return _.splice(0,0,a),_.splice(u?3:1,0,h),_},No=[2,3,1,0],Sc=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[1]*t.group;if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},nu=(e,t)=>{let r=e.kernelShape.slice();for(let u=2;u{let t=Bn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,u=e.group,a=e.kernel_shape,c=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:o,format:r,dilations:i,group:u,kernelShape:a,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},xc=(e,t,r)=>{let o=nu(r,t),i=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let L=Vn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,i),N=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=N);let K=[t[0],N];t.length===3&&K.push(t[2]),e.compute(eu(K,o,L),{inputs:K})}else e.compute(Mo(t,o));return}let u=t.length===3,a=t[0].dims[i?1:2],c=t[0].dims[i?2:3],p=t[0].dims[i?3:1],h=t[1].dims[2],d=t[1].dims[3],y=Vn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,i),w=y[i?1:2],_=y[i?2:3],v=y[i?3:1],S=i&&h===a&&d===c&&r.pads[0]===0&&r.pads[1]===0;if(S||h===1&&d===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let R=y[0],L,N,K,Q=[];if(i){let se=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=se),S){let Ce=a*c*p;L=t[0].reshape([1,R,Ce]),N=se.reshape([1,Ce,v]),K=[1,R,v]}else L=t[0].reshape([R,a*c,p]),N=se.reshape([1,p,v]),K=[R,w*_,v];Q.push(L),Q.push(N)}else L=t[0].reshape([R,p,a*c]),N=t[1].reshape([1,v,p]),K=[R,v,w*_],Q.push(N),Q.push(L);u&&Q.push(t[2]);let he=K[2],W=Q[0].dims[Q[0].dims.length-1];he<8&&W<8?e.compute(Vo(Q,o,y,K,i),{inputs:Q}):e.compute(Un(Q,o,y,K,i),{inputs:Q});return}let A=!0,I=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let x=[t[0],I];u&&x.push(t[2]);let E=i?w*_:v,P=i?v:w*_,O=h*d*p;e.compute(Qs(x,o,y,E,P,O,u,A),{inputs:x})},Cc=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&o.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],u=[1].concat(t.strides),a=[1].concat(t.dilations),c=[1].concat(t.kernelShape),p=nu({...t,pads:i,strides:u,dilations:a,kernelShape:c},o);e.compute(Mo(o,p,h=>r?[h[0],h[2],h[3]]:[]))},Ho=(e,t)=>{Sc(e.inputs,t),e.inputs[0].dims.length===3?Cc(e,t):xc(e,e.inputs,t)}});var Ac,ou,iu=Y(()=>{"use strict";ye();Lt();_e();Ft();zn();zo();Fr();Ac=(e,t=!1,r,o,i=4)=>{let u=I=>{switch(I){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${o}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${I} is not supported.`)}},a=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,c=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",d=e?"row":"col",y=e?"col":"row",w=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${d} / outWidth;\n let outCol = ${d} % outWidth;\n\n let WRow = ${y} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${y} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${p}) || fract(xR) > 0.0) {\n return ${o}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${h}) || fract(xC) > 0.0) {\n return ${o}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${y} % inChannels;\n ${a}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,_=e?`\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${w}\n }\n return ${o}(0.0);`:`\n let col = colIn * ${i};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${w}\n }\n return ${o}(0.0);`,v=`\n let col = colIn * ${i};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${u(i)}\n }\n return ${o}(0.0);\n `,S=St(r,o);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?_:v}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?v:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${o}) {\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${c}\n ${Dn(t)}\n ${S}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value;\n }\n }`},ou=(e,t,r,o,i,u,a,c)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],d=r[0],y=p?r[2]:r[3],w=p?r[1]:r[2],_=p?r[3]:r[1],v=p&&h%4===0&&h%3&&_%4===0,S=p?_:y*w,A=p?y*w:_,I=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(S/I[0]/x[0]),Math.ceil(A/I[1]/x[1]),Math.ceil(d/I[2]/x[2])];Ve("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let P=v?4:1,O=Math.max(I[0]*P,I[1]),R=v?4:1,L=[t.kernelShape[p?1:2],t.kernelShape[p?2:3]],N=[L[0]+(t.dilations[0]<=1?0:(L[0]-1)*(t.dilations[0]-1)),L[1]+(t.dilations[1]<=1?0:(L[1]-1)*(t.dilations[1]-1))],K=[N[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),N[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Q=[{type:6,data:o},{type:6,data:i},{type:6,data:u},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:L},{type:6,data:K}];xt(t,Q),Q.push(...Z(e[0].dims,e[1].dims));let he=["rank","rank"];a&&(Q.push(...Z(e[2].dims)),he.push("rank")),Q.push(...Z(r));let W=se=>{let Ce=U("x",e[0].dataType,e[0].dims.length,R),We=U("w",e[1].dataType,e[1].dims.length,1),ee=j("result",e[0].dataType,r.length,R),ae=[Ce,We],Ae="";if(a){let ue=U("bias",e[2].dataType,e[2].dims.length,R);ae.push(ue),Ae+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${ue.type.value} {\n return bias[coords.${p?"w":"y"}${v?"/ 4":""}];\n }`}let me=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:L.length},{name:"pads",type:"i32",length:K.length}];Ct(t,me);let ie=De(e[0].dataType,1);if(ie!=="f16"&&ie!=="f32")throw new Error(`elemType ${ie} is not supported.`);return`\n ${Mn("uniforms.result_strides")}\n ${se.registerUniforms(me).declareVariables(...ae,ee)};\n ${Ae}\n ${Ac(p,a,t,Ce.type.value,P)}\n ${v?Hr(x,I,ie,void 0,!p,O):Lr(x,I,ie,void 0,!p,O,!1,void 0,c)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${x};${I};${v}`,inputDependencies:he},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:Q}),getShaderSource:W}}});var Ic,Lo,au=Y(()=>{"use strict";ye();Lt();Se();_e();Ic=(e,t,r,o,i,u=!1,a,c,p=!1)=>{let h=p?1:2,d=p?2:3,y=p?3:1,w=u?2:1,_=`\n fn setOutputAtIndex(flatIndex : u32, value : ${u?`vec4<${a}>`:a}) {\n result[flatIndex] = ${u?`vec4<${a}>`:a}(value);\n }`;o&&(_+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${u?`vec4<${a}>`:a} {\n return bias[coords.${p?"w":"y"}${u?"/ 4":""}];\n }`);let v=u?4:1,S=U("W",t[1].dataType,t[1].dims.length,v),A=U("Dy",t[0].dataType,t[0].dims.length,v),I=[A,S];o&&I.push(U("bias",t[2].dataType,[r[y]].length,v));let x=j("result",t[0].dataType,r.length,v),E=`{\n let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${i?"global_id.y":"workgroup_id.y"} * ${w};\n let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${w}>;\n for (var i = 0; i < ${w}; i++) {\n dotProd[i] = vec4<${a}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${A.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${y}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${w}; i = i + 1) {\n let value = dotProd[i] + ${o?"bias[c+i]":`vec4<${a}>(0.0)`};\n ${x.set("batch","r","c + i","d1","value")};\n }\n }`,P=`\n let outputIndices = ${x.offsetToIndices("global_idx")};\n let batch = ${x.indicesGet("outputIndices",0)};\n let d1 = ${x.indicesGet("outputIndices",y)};\n let r = ${x.indicesGet("outputIndices",h)};\n let c = ${x.indicesGet("outputIndices",d)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${a}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${h}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${d}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${p?A.get("batch","idyR","idyC","inputChannel"):A.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${S.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${o?"bias[d1]":`${a}(0.0)`};\n ${x.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(c).declareVariables(...I,x)}\n ${_}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${u?E:P}}`},Lo=(e,t,r)=>{let o=e.length>2,i=t.outputShape,u=M.size(i),a=[Math.ceil(u/64),1,1];Ve("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let c=t.format==="NHWC",p=["rank","rank"],h=[t.strides[0],t.strides[1]],d=[t.kernelShape[c?1:2],t.kernelShape[c?2:3]],y=[t.dilations[0],t.dilations[1]],w=[d[0]+(t.dilations[0]<=1?0:(t.kernelShape[c?1:2]-1)*(t.dilations[0]-1)),d[1]+(t.dilations[1]<=1?0:(t.kernelShape[c?2:3]-1)*(t.dilations[1]-1))],_=[w[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),w[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],v=!1,S=t.group,A=e[1].dims,I=A[0]/S,x=A[1],E=[{type:12,data:u},{type:12,data:h},{type:12,data:d},{type:12,data:y},{type:12,data:w},{type:6,data:_},{type:12,data:I},{type:12,data:x},...Z(e[0].dims,e[1].dims)];o&&(E.push(...Z(e[2].dims)),p.push("rank")),E.push(...Z(i));let P=a[1]===1&&a[2]===1,O=R=>{let L=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:h.length},{name:"filter_dims",type:"u32",length:d.length},{name:"dilations",type:"u32",length:d.length},{name:"effective_filter_dims",type:"u32",length:w.length},{name:"pads",type:"i32",length:_.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],N=De(e[0].dataType);return`${Ic(R,e,i,o,P,v,N,L,c)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:p},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}],programUniforms:E}),getShaderSource:O}}});var Tc,Ec,Pc,su,uu,kc,Oc,Rc,Bc,du,lu=Y(()=>{"use strict";iu();au();Ft();Sr();Tc=(e,t,r,o,i,u)=>(e-1)*t+r+(o-1)*i+1-u,Ec=(e,t,r,o,i)=>{let u=Math.floor(e/2);t==="SAME_UPPER"?(r[o]=u,r[i]=e-u):t==="SAME_LOWER"&&(r[o]=e-u,r[i]=u)},Pc=(e,t,r,o,i,u,a,c,p,h)=>{let d=e.length-2,y=h.length===0;if(p.length===0)for(let v=0;v{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((y,w)=>y*w,1)===0){r.length=0;for(let y=2;yy+w,0)===0){let y=t[0].dims.length-2;p=new Array(y).fill(1)}let h=e.strides.slice();if(h.reduce((y,w)=>y+w,0)===0){let y=t[0].dims.length-2;h=new Array(y).fill(1)}Pc(c,r,p,e.autoPad,e.group,i,h,o,a,u);let d=Object.assign({},e);return Object.assign(d,{kernelShape:r,pads:i,outputPadding:a,outputShape:u,dilations:p,strides:h}),d},uu=e=>{let t=Bn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,u=e.group,a=e.kernelShape,c=e.pads,p=e.strides,h=e.wIsConst(),d=e.outputPadding,y=e.outputShape;return{autoPad:o,format:r,dilations:i,group:u,kernelShape:a,outputPadding:d,outputShape:y,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},kc=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[0];if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let u=e[0].dims.length-2;if(t.dilations.reduce((d,y)=>d+y,0)>0&&t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.reduce((d,y)=>d+y,0)>0&&t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.reduce((d,y)=>d+y,0)>0&&t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.outputPadding.length!==u&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${u}D`);if(t.kernelShape.reduce((d,y)=>d+y,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Oc=[2,3,1,0],Rc=(e,t,r)=>{let o=su(r,t),i=r.format==="NHWC",u=o.outputShape,a=u[i?3:1],c=t[0].dims[i?3:1];if(o.group!==1||a===1&&c===1){e.compute(Lo(t,o));return}let p=u[i?1:2],h=u[i?2:3],d=t[1].dims[2],y=t[1].dims[3],w=i?p*h:a,_=i?a:p*h,v=d*y*c,S=!0,A=e.kernelCustomData.wT??e.compute(yt(t[1],Oc),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=A);let I=[t[0],A],x=t.length===3;x&&(!i&&t[2].dims.length===1?I.push(t[2].reshape([t[2].dims[0],1,1])):I.push(t[2])),e.compute(ou(I,o,u,w,_,v,x,S),{inputs:I})},Bc=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&o.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let u=t.dilations;(u.length===0||u[0]===0)&&(u=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],a=[1].concat(a),u=[1].concat(u),i=[1].concat(i);let p=su({...t,pads:c,strides:a,dilations:u,kernelShape:i},o);e.compute(Lo(o,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]]))},du=(e,t)=>{kc(e.inputs,t),e.inputs[0].dims.length===3?Bc(e,t):Rc(e,e.inputs,t)}});var Dc,cu,pu,mu=Y(()=>{"use strict";ye();Se();Ze();_e();Dc=(e,t,r,o)=>{let i=M.size(t),u=t.length,a=U("input",e,u),c=j("output",e,u),p=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=M.normalizeAxis(p,u),d=y=>{let w=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,_=fe("uniforms.input_shape","uniforms.axis",u),v=o.reverse?w+(o.exclusive?" + 1":""):"0",S=o.reverse?_:w+(o.exclusive?"":" + 1");return`\n ${y.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,c)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${c.offsetToIndices("global_idx")};\n var sum = ${c.type.value}(0);\n let first : i32 = ${v};\n let last : i32 = ${S};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${a.getByIndices("inputIndices")};\n }\n ${c.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:o.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...Z(t,t)]}),getShaderSource:d}},cu=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,i=e.inputs[1];e.compute(Dc(o,r,i,t),{inputs:[0]})},pu=e=>{let t=e.exclusive===1,r=e.reverse===1;return ve({exclusive:t,reverse:r})}});var zc,Mc,Uc,fu,hu,gu=Y(()=>{"use strict";ye();Se();Ze();_e();zc=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Mc=(e,t,r,o)=>{let i=[];i.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let u=0;u{let r,o,i,u,a,c,p=t.format==="NHWC",h=t.blocksize,d=t.mode==="DCR";p?([r,o,i,u]=e.dims,a=d?[r,o,i,h,h,u/h**2]:[r,o,i,u/h**2,h,h],c=d?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,o,i,u]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=d?[r,h,h,u/h**2,o,i]:[r,u/h**2,h,h,o,i],c=d?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let y=e.reshape(a),w=y.dims.length,_=e.dataType,v=U("a",_,w),S=j("output",_,w),A=I=>`\n ${I.registerUniform("output_size","u32").declareVariables(v,S)}\n\n ${Mc(c,w,v,S)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${S.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${S.setByOffset("global_idx",v.getByIndices("aIndices"))}\n }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:I=>{let x=p?[r,o*h,i*h,u/h**2]:[r,u/h**2,o*h,i*h],E=M.size(x),P=y.dims,O=M.sortBasedOnPerm(P,c);return{outputs:[{dims:x,dataType:I[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:[{type:12,data:E},...Z(P,O)]}},getShaderSource:A}},fu=(e,t)=>{zc(e.inputs),e.compute(Uc(e.inputs[0],t))},hu=e=>ve({blocksize:e.blocksize,mode:e.mode,format:e.format})});var Fo,Wn,yu,Vc,Wc,qo,jo,bu,Nc,wu,vu,$u=Y(()=>{"use strict";ye();Se();Ze();_e();Fo="[a-zA-Z]|\\\\.\\\\.\\\\.",Wn="("+Fo+")+",yu="^"+Wn+"$",Vc="("+Wn+",)*"+Wn,Wc="^"+Vc+"$",qo=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let o=this.symbolToIndices.get(t);o===void 0?o=[r]:o.push(r),this.symbolToIndices.set(t,o)}},jo=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[o,i]=r.includes("->")?r.split("->",2):[r,""];if(!o.match(RegExp(Wc)))throw new Error("Invalid LHS term");if(o.split(",").forEach((c,p)=>{let h=t[p].dims.slice();if(!c.match(RegExp(yu)))throw new Error("Invalid LHS term");let d=this.processTerm(c,!0,h,p);this.lhs.push(d)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([c,p])=>p.count===1||c==="...").map(([c])=>c).join("");else if(!i.match(RegExp(Wn)))throw new Error("Invalid RHS");i.match(RegExp(Fo,"g"))?.forEach(c=>{if(c==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let p=this.symbolToInfo.get(c);if(p===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(p.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(t,r,o){let i=this.symbolToInfo.get(t);if(i!==void 0){if(i.dimValue!==r&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(o)}else i={count:1,dimValue:r,inputIndices:[o]};this.symbolToInfo.set(t,i)}processTerm(t,r,o,i=-1){let u=o.length,a=!1,c=[],p=0;if(!t.match(RegExp(yu))&&!r&&t!=="")throw new Error("Invalid LHS term");let h=t.match(RegExp(Fo,"g")),d=new qo(i);return h?.forEach((y,w)=>{if(y==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let _=u-h.length+1;if(_<0)throw new Error("Ellipsis out of bounds");if(c=o.slice(p,p+_),this.hasEllipsis){if(this.ellipsisDims.length!==c.length||this.ellipsisDims.toString()!==c.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=c;else throw new Error("Ellipsis must be specified in the LHS");for(let v=0;ve+"_max",Nc=(e,t,r,o)=>{let u=e.map(d=>d.length).map((d,y)=>U(`input${y}`,t,d)),a=M.size(o),c=j("output",t,o.length),p=[...r.symbolToInfo.keys()].filter(d=>!r.rhs.symbolToIndices.has(d)),h=d=>{let y=[],w="var prod = 1.0;",_="var sum = 0.0;",v="sum += prod;",S=[],A=[],I=[],x=[],E=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((O,R)=>{if(r.rhs.symbolToIndices.has(R)){let L=r.rhs.symbolToIndices.get(R)?.[0];L!==void 0&&r.lhs.forEach((N,K)=>{if(O.inputIndices.includes(K)){let Q=N.symbolToIndices.get(R);if(Q===void 0)throw new Error("Invalid symbol error");Q.forEach(he=>{y.push(`${u[K].indicesSet(`input${K}Indices`,he,c.indicesGet("outputIndices",L))}`)})}})}else r.lhs.forEach((L,N)=>{if(O.inputIndices.includes(N)){let K=L.symbolToIndices.get(R);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(Q=>{S.push(`${u[N].indicesSet(`input${N}Indices`,Q,`${R}`)}`)}),x.push(`prod *= ${u[N].getByIndices(`input${N}Indices`)};`)}}),A.push(`for(var ${R}: u32 = 0; ${R} < uniforms.${bu(R)}; ${R}++) {`),I.push("}")});let P=E?[...y,`let sum = ${u.map((O,R)=>O.getByIndices(`input${R}Indices`)).join(" * ")};`]:[...y,_,...A,...S,w,...x,v,...I];return`\n ${d.registerUniforms(p.map(O=>({name:`${bu(O)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,c)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${c.offsetToIndices("global_idx")};\n ${u.map((O,R)=>`var input${R}Indices: ${u[R].type.indices};`).join(`\n`)}\n ${P.join(`\n`)};\n ${c.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let d=p.filter(w=>r.symbolToInfo.has(w)).map(w=>({type:12,data:r.symbolToInfo.get(w)?.dimValue||0}));d.push({type:12,data:a});let y=e.map((w,_)=>[...Z(w)]).reduce((w,_)=>w.concat(_),d);return y.push(...Z(o)),{outputs:[{dims:o,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:y}},getShaderSource:h}},wu=(e,t)=>{let r=new jo(e.inputs,t.equation),o=r.outputDims,i=e.inputs.map((u,a)=>u.dims);e.compute(Nc(i,e.inputs[0].dataType,r,o))},vu=e=>{let t=e.equation.replace(/\\s+/g,"");return ve({equation:t})}});var Gc,_u,Hc,Lc,Su,xu=Y(()=>{"use strict";ye();Se();_e();Gc=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=r.length{let r=e.length-t.length,o=[];for(let i=0;ie.length>t.length?_u(e,t):_u(t,e),Lc=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=Hc(t,r),i=e[0].dataType,u=i===9?4:1,a=Math.ceil(M.size(o)/u),c=h=>{let d=U("input",i,t.length,u),y=j("output",i,o.length,u),w;if(i===9){let _=(v,S,A="")=>`\n let outputIndices${S} = ${y.offsetToIndices(`outputOffset + ${S}u`)};\n let offset${S} = ${d.broadcastedIndicesToOffset(`outputIndices${S}`,y)};\n let index${S} = offset${S} / 4u;\n let component${S} = offset${S} % 4u;\n ${v}[${S}] = ${A}(${d.getByOffset(`index${S}`)}[component${S}]);\n `;w=`\n let outputOffset = global_idx * ${u};\n var data = vec4(0);\n ${_("data",0,"u32")}\n ${_("data",1,"u32")}\n ${_("data",2,"u32")}\n ${_("data",3,"u32")}\n ${y.setByOffset("global_idx","data")}\n }`}else w=`\n let outputIndices = ${y.offsetToIndices("global_idx")};\n let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",y)};\n ${y.setByOffset("global_idx",d.getByOffset("inputOffset"))}\n }`;return`\n ${h.registerUniform("vec_size","u32").declareVariables(d,y)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${w}`},p=[{type:12,data:a},...Z(t,o)];return{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p})}},Su=e=>{Gc(e.inputs),e.compute(Lc(e.inputs),{inputs:[0]})}});var Fc,Cu,Au=Y(()=>{"use strict";ye();Se();_e();Rn();Fc=e=>{let t=e[0].dataType,r=M.size(e[0].dims),o=M.size(e[1].dims),i=o%4===0,u=a=>{let c=U("x",t,[1],4),p=U("bias",t,[1],4),h=j("y",t,[1],4),d=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],y=_=>`\n let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;\n let bias${_} = ${p.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,w=i?`\n let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${y(0)}${y(1)}${y(2)}${y(3)}\n let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(d).declareVariables(c,p,h)}\n\n ${Bo(et(t))}\n\n ${a.mainStart(or)}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${c.getByOffset("global_idx")};\n ${w}\n let x_in = x + bias;\n ${h.setByOffset("global_idx",Do("x_in"))}\n }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:u,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:o}],dispatchGroup:{x:Math.ceil(r/or/4)}})}},Cu=e=>{e.inputs.length<2||M.size(e.inputs[1].dims)===0?Bs(e):e.compute(Fc(e.inputs))}});var qc,jc,Iu,Tu,Eu=Y(()=>{"use strict";ye();Se();Ze();_e();qc=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},jc=(e,t)=>{let r=e[0].dims,o=e[1].dims,i=r.length,u=M.normalizeAxis(t.axis,i),a=r.slice(0);a.splice(u,1,...o);let c=r[u],p=e[0].dataType===9?4:1,h=Math.ceil(M.size(a)/p),d=[{type:12,data:h},{type:6,data:c},{type:12,data:u},...Z(e[0].dims,e[1].dims,a)],y=w=>{let _=U("data",e[0].dataType,e[0].dims.length,p),v=U("inputIndices",e[1].dataType,e[1].dims.length),S=j("output",e[0].dataType,a.length,p),A=x=>{let E=o.length,P=`var indicesIndices${x} = ${v.type.indices}(0);`;for(let O=0;O1?`indicesIndices${x}[${O}]`:`indicesIndices${x}`} = ${a.length>1?`outputIndices${x}[uniforms.axis + ${O}]`:`outputIndices${x}`};`;P+=`\n var idx${x} = ${v.getByIndices(`indicesIndices${x}`)};\n if (idx${x} < 0) {\n idx${x} = idx${x} + uniforms.axisDimLimit;\n }\n var dataIndices${x} : ${_.type.indices};\n `;for(let O=0,R=0;O1?`dataIndices${x}[${O}]`:`dataIndices${x}`} = u32(idx${x});`,R+=E):(P+=`${i>1?`dataIndices${x}[${O}]`:`dataIndices${x}`} = ${a.length>1?`outputIndices${x}[${R}]`:`outputIndices${x}`};`,R++);return P},I;if(e[0].dataType===9){let x=(E,P,O="")=>`\n let outputIndices${P} = ${S.offsetToIndices(`outputOffset + ${P}u`)};\n ${A(P)};\n let offset${P} = ${_.indicesToOffset(`dataIndices${P}`)};\n let index${P} = offset${P} / 4u;\n let component${P} = offset${P} % 4u;\n ${E}[${P}] = ${O}(${_.getByOffset(`index${P}`)}[component${P}]);\n `;I=`\n let outputOffset = global_idx * ${p};\n var value = vec4(0);\n ${x("value",0,"u32")}\n ${x("value",1,"u32")}\n ${x("value",2,"u32")}\n ${x("value",3,"u32")}\n ${S.setByOffset("global_idx","value")}\n `}else I=`\n let outputIndices = ${S.offsetToIndices("global_idx")};\n ${A("")};\n let value = ${_.getByIndices("dataIndices")};\n ${S.setByOffset("global_idx","value")};\n `;return`\n ${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,v,S)}\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${I}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}),getShaderSource:y}},Iu=e=>ve({axis:e.axis}),Tu=(e,t)=>{let r=e.inputs;qc(r),e.compute(jc(e.inputs,t))}});var Kc,Yc,Pu,ku,Ou=Y(()=>{"use strict";ye();Se();Ze();_e();Kc=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Yc=(e,t)=>{let r=e[0].dims,o=e[0].dataType,i=r.length,u=e[1].dims,a=e[1].dataType,c=M.normalizeAxis(t.axis,i),p=r[c],h=u.slice(0),d=M.size(h),y=U("input",o,i),w=U("indicesInput",a,u.length),_=j("output",o,h.length),v=[{type:12,data:d},{type:6,data:p},{type:12,data:c}];return v.push(...Z(r,u,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:v}),getShaderSource:I=>`\n ${I.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(y,w,_)}\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${_.offsetToIndices("global_idx")};\n\n var idx = ${w.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${y.type.indices}(outputIndices);\n ${y.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${y.getByIndices("inputIndices")};\n\n ${_.setByOffset("global_idx","value")};\n }`}},Pu=e=>ve({axis:e.axis}),ku=(e,t)=>{let r=e.inputs;Kc(r),e.compute(Yc(e.inputs,t))}});var Zc,Xc,Ru,Bu,Du=Y(()=>{"use strict";ye();Se();_e();Zc=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Xc=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[i,u,a]=Sn.getShapeOfGemmResult(r,t.transA,o,t.transB,e.length===3?e[2].dims:void 0),c=[i,u];if(!c)throw new Error("Can\'t use gemm on the given tensors");let p=M.size(c),h=[{type:12,data:p},{type:12,data:i},{type:12,data:u},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],d=["type","type"];e.length===3&&(h.push(...Z(e[2].dims)),d.push("rank")),h.push(...Z(c));let y=w=>{let _="";t.transA&&t.transB?_="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?_="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?_="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(_="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let v=t.alpha===1?"":"value *= uniforms.alpha;",S=U("a",e[0].dataType,e[0].dims),A=U("b",e[1].dataType,e[1].dims),I=S.type.value,x=null,E=[S,A];e.length===3&&(x=U("c",e[2].dataType,e[2].dims.length),E.push(x));let P=j("output",e[0].dataType,c.length);E.push(P);let O=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`\n ${w.registerUniforms(O).declareVariables(...E)}\n\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${I}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${_}\n }\n\n ${v}\n ${(()=>x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",P)}; value += ${I}(uniforms.beta) * ${x.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:y}},Ru=e=>{let t=e.transA,r=e.transB,o=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:o,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Bu=(e,t)=>{Zc(e.inputs),e.compute(Xc(e.inputs,t))}});var Qc,Jc,ep,zu,Mu=Y(()=>{"use strict";ye();Se();_e();Qc=(e,t)=>{let r=e[0].dims,o=r,i=2,u=M.sizeToDimension(r,i),a=M.sizeFromDimension(r,i),c=Me(a),p=a/c,h=[r[0],r[1],p],d=["rank","type","type"],y=[{type:12,data:a},{type:12,data:p}];y.push(...Z(h,h));let w=_=>{let v=U("x",e[0].dataType,h.length,c),S=U("scale",e[1].dataType,e[1].dims),A=U("bias",e[2].dataType,e[2].dims),I=j("output",e[0].dataType,h.length,c),x=[v,S,A,I],E=v.type.value,P=c===1?"f32":`vec${c}`,O=64,R=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${P}, ${O}>;\n const workgroupSize = ${O}u;\n ${_.registerUniforms(R).declareVariables(...x)}\n ${_.mainStart(O)}\n let norm = global_idx / workgroupSize;\n let batch = norm / uniforms.x_shape[1];\n let channel = norm % uniforms.x_shape[1];\n let localIndex = local_id.x;\n\n // initialize workgroup memory\n var initial = ${P}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${P}(${v.get("batch","channel","h")});\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the mean of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n meanShared = ${_t("workgroupShared[0]",c)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${P}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${P}(${v.get("batch","channel","h")}) - ${P}(meanShared);\n initial = initial + deviation * deviation;\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the sum of square of deviation of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n squaredNormShared = ${_t("workgroupShared[0]",c)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${S.getByOffset("channel")});\n let channelShift = f32(${A.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${v.get("batch","channel","h")} * ${E}(${P}(channelScale)) + ${E}(${P}(channelShift));\n ${I.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${c}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:u},programUniforms:y}),getShaderSource:w}},Jc=(e,t,r,o,i,u,a,c)=>{let p=Me(a),h=64,d=p===1?"vec2f":`mat2x${p}f`,y=p===1?"f32":`vec${p}f`,w=(R,L)=>`${d}(${R}, ${L})`,_=i*a/p,v=Math.ceil(u/h),S=["type"],A=[{type:12,data:v},{type:12,data:u},{type:12,data:Math.floor(a/p)},{type:12,data:Math.floor(u*a/p)}],I=R=>{let L=U("input",t.dataType,t.dims,p);return`\n ${R.declareVariables(L)}\n @group(0) @binding(1) var output : array<${d}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${R.mainStart(h)}\n let currentImageNumber = global_idx / ${h} / uniforms.C;\n let currentChannelNumber = (global_idx / ${h}) % uniforms.C;\n let wgOffset = local_id.x * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${$t("f32",p)};\n var squaredSum = ${$t("f32",p)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${y}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${w("sum","squaredSum")};\n }`},x=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:[i,a,h,2],dataType:1}],dispatchGroup:{x:i*a/p},programUniforms:A}),getShaderSource:I},{inputs:[t],outputs:[-1]})[0],E=[{type:12,data:_},{type:12,data:u},{type:12,data:Math.floor(a/p)},{type:12,data:Math.floor(h*a/p)}],P=["type","type","type"],O=R=>{let L=U("scale",r.dataType,r.dims,p),N=U("bias",o.dataType,o.dims,p);return`\n @group(0) @binding(0) var input : array<${d}>;\n @group(0) @binding(1) var scale : array<${L.type.storage}>;\n @group(0) @binding(2) var bias : array<${N.type.storage}>;\n @group(0) @binding(3) var output : array<${d}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${R.mainStart()}\n ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")}\n let currentImageNumber = global_idx / uniforms.C;\n let currentChannelNumber = global_idx % uniforms.C;\n\n let offset = currentImageNumber * uniforms.image_size;\n var sum = ${$t("f32",p)};\n var squaredSum = ${$t("f32",p)};\n for (var i: u32 = 0; i < min(${h}, uniforms.H); i++) {\n let value = input[offset + i + currentChannelNumber * ${h}];\n sum += value[0];\n squaredSum += value[1];\n }\n sum = sum / f32(uniforms.H);\n squaredSum = squaredSum / f32(uniforms.H);\n let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${c}));\n let channelScale = invStdDev * ${y}(scale[currentChannelNumber]);\n let channelShift = ${y}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${w("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${c}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:[i,a,2],dataType:1}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:E}),getShaderSource:O},{inputs:[x,r,o],outputs:[-1]})[0]},ep=(e,t,r)=>{let o=t[0].dims,i=o,u=o[0],a=o[o.length-1],c=M.sizeFromDimension(o,1)/a,p=Me(a),h=M.size(i)/p,d=[{type:12,data:c},{type:12,data:Math.floor(a/p)}],y=["type","type"],w=Jc(e,t[0],t[1],t[2],u,c,a,r.epsilon),_=v=>{let S=De(t[0].dataType),A=p===1?"vec2f":`mat2x${p}f`,I=p===1?S:`vec${p}<${S}>`,x=U("input",t[0].dataType,t[0].dims,p),E=j("output",t[0].dataType,i,p);return`\n @group(0) @binding(0) var input : array<${x.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${A}>;\n @group(0) @binding(2) var output : array<${E.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${v.mainStart()}\n let currentImageNumber = global_idx / (uniforms.C * uniforms.H);\n let currentChannelNumber = global_idx % uniforms.C;\n\n let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber;\n let scale = scaleInput[scaleOffset];\n output[global_idx] = fma(input[global_idx], ${I}(scale[0]), ${I}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}),getShaderSource:_},{inputs:[t[0],w]})},zu=(e,t)=>{t.format==="NHWC"?ep(e,e.inputs,t):e.compute(Qc(e.inputs,t))}});var tp,rp,Uu,Vu=Y(()=>{"use strict";ye();Se();_e();tp=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},rp=(e,t,r)=>{let o=t.simplified,i=e[0].dims,u=e[1],a=!o&&e[2],c=i,p=M.normalizeAxis(t.axis,i.length),h=M.sizeToDimension(i,p),d=M.sizeFromDimension(i,p),y=M.size(u.dims),w=a?M.size(a.dims):0;if(y!==d||a&&w!==d)throw new Error(`Size of X.shape()[axis:] == ${d}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${y} and bias size of ${w}`);let _=[];for(let O=0;O1,x=r>2,E=O=>{let R=De(e[0].dataType),L=[U("x",e[0].dataType,e[0].dims,v),U("scale",u.dataType,u.dims,v)];a&&L.push(U("bias",a.dataType,a.dims,v)),L.push(j("output",e[0].dataType,c,v)),I&&L.push(j("mean_data_output",1,_)),x&&L.push(j("inv_std_output",1,_));let N=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${O.registerUniforms(N).declareVariables(...L)}\n ${O.mainStart()}\n ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${$t("f32",v)};\n var mean_square_vector = ${$t("f32",v)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${ir(R,v,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${_t("mean_vector",v)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${_t("mean_square_vector",v)} / uniforms.norm_size ${o?"":"- mean * mean"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${ir(R,v,"x[j + offset]")};\n let f32scale = ${ir(R,v,"scale[j]")};\n output[j + offset] = ${L[0].type.value}((f32input ${o?"":"- mean"}) * inv_std_dev * f32scale\n ${a?`+ ${ir(R,v,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${x?"inv_std_output[global_idx] = inv_std_dev":""};\n }`},P=[{dims:c,dataType:e[0].dataType}];return I&&P.push({dims:_,dataType:1}),x&&P.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${v};${r};${o}`,inputDependencies:S},getRunData:()=>({outputs:P,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:A}),getShaderSource:E}},Uu=(e,t)=>{tp(e.inputs),e.compute(rp(e.inputs,t,e.outputCount))}});var np,op,Wu,Nu,Gu=Y(()=>{"use strict";ye();Se();Ze();_e();np=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],o=r.dims.length;if(r.dims[o-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),u=t.blockSize/8*t.bits,a=e[1];if(!M.areEqual(a.dims,[t.n,i,u]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let p=e[2].dims;if(M.size(p)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,y=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(M.size(d)!==y)throw new Error("zeroPoints input size error.")}},op=(e,t,r,o)=>{let i=e[0].dims,u=i.length,a=Math.floor((t.k+t.blockSize-1)/t.blockSize),c=i[u-2],p=t.k,h=t.n,d=i.slice(0,u-2),y=M.size(d),_=t.blockSize/8*t.bits/4,v=e[0].dataType,S=Me(c),A=Me(t.k),I=Me(_),x=tr(v),E=c*a*x,P=Math.floor(o/E),O=a<=r[0]&&P>0,R=!O||P>=4?Me(h):P>=2&&Me(h)>=2?2:1,L=d.concat([c,h]),N=M.size(L)/R/S,K=O?[]:[{type:12,data:N},{type:12,data:t.blockSize}],Q=[y,c,p/A],he=M.convertShape(e[1].dims).slice();he.splice(-1,1,_/I),K.push(...Z(Q)),K.push(...Z(he)),K.push(...Z(e[2].dims)),e.length===4&&K.push(...Z(M.convertShape(e[3].dims)));let W=[y,c,h/R];K.push(...Z(W));let se=Ce=>{let We=Q.length,ee=U("a",e[0].dataType,We,A),ae=U("b",12,he.length,I),Ae=U("scales",e[2].dataType,e[2].dims.length),me=[ee,ae,Ae],ie=e.length===4?U("zero_points",12,e[3].dims.length):void 0;ie&&me.push(ie);let ue=W.length,le=j("output",e[0].dataType,ue,R),qe=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],G=De(e[0].dataType),ne=(()=>{switch(A){case 1:return`array<${G}, 8>`;case 2:return`mat4x2<${G}>`;case 4:return`mat2x4<${G}>`;default:throw new Error(`${A}-component is not supported.`)}})(),xe=`\n for (var word: u32 = 0; word < ${_}; word += ${I}) {\n ${ae.indicesSet("b_indices","2","word")};\n let b_data = ${ae.getByIndices("b_indices")};\n for (var i: u32 = 0; i < ${I}; i++) {\n let b_value: u32 = ${I===1?"b_data":"b_data[word + i]"};\n let b_mask: u32 = 0x0F0F0F0Fu;\n let b_value_lower: vec4 = unpack4xU8(b_value & b_mask);\n let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask);\n let b_quantized_values = ${ne}(${Array.from({length:4},(Be,Ge)=>`${G}(b_value_lower[${Ge}]), ${G}(b_value_upper[${Ge}])`).join(", ")});\n let b_dequantized_values = ${(()=>A===1?`${ne}(${Array.from({length:8},(Be,Ge)=>`(b_quantized_values[${Ge}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ne}(${Array(8).fill("zero_point").join(",")})) * scale;`)()};\n // Number of B elements per 32-bit word is 32/bits = 32/4 = 8\n for (var m: u32 = 0; m < ${O?c:S}u; m++) {\n ${ee.indicesSet("a_indices",We-2,O?"m":`row * ${S} + m`)};\n ${ee.indicesSet("a_indices",We-1,"word_offset")};\n var input_offset = ${ee.indicesToOffset("a_indices")};\n var a_data: ${ne};\n for (var j: u32 = 0; j < ${8/A}; j++) {\n a_data[j] = ${ee.getByOffset("input_offset")};\n input_offset++;\n }\n ${O?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${R>1?"[c]":""} += ${Array.from({length:8/A},(Be,Ge)=>`${A===1?`a_data[${Ge}] * b_dequantized_values[${Ge}]`:`dot(a_data[${Ge}], b_dequantized_values[${Ge}])`}`).join(" + ")};\n }\n word_offset += ${8/A};\n }\n }`,Ke=ie?`\n zero_point_offset += 4;\n if (zero_point_offset == 32) {\n zero_point_offset = 0;\n zero_point_index++;\n zero_point_word = ${ie.getByOffset("zero_point_index")};\n }`:"";return O?`\n var workgroup_shared: array<${le.type.value}, ${c*a}>;\n ${Ce.declareVariables(...me,le)}\n ${Ce.mainStart([a,1,1])}\n var a_indices: ${ee.type.indices};\n var block = local_id.x;\n var col = workgroup_id.y;\n var batch = workgroup_id.z;\n ${ee.indicesSet("a_indices","0","batch")};\n // Two zero points are packed into one byte when uniforms.bits is 4.\n for (var c: u32 = 0; c < ${R}; c++) {\n let col_times_components_plus_c = col * ${R} + c;\n ${ie?`\n var zero_point_bytes_per_col: u32 = (${a} + 1) / 2;\n var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u);\n var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u;\n var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u;\n var zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n var zero_point_word: u32 = ${ie.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""}\n var b_indices: ${ae.type.indices};\n ${ae.indicesSet("b_indices","0","col_times_components_plus_c")};\n // The scale and zero points are computed per block.\n var scales_index = col_times_components_plus_c * ${a} + block;\n let scale = ${Ae.getByOffset("scales_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${G}(${ie?"(zero_point_word) & 0xFu":8});\n ${ae.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block * ${t.blockSize/A};\n var workgroup_shared_offset: u32 = block * ${c};\n ${xe}\n }\n workgroupBarrier();\n if (local_id.x == 0u) {\n var output_indices: ${le.type.indices};\n ${le.indicesSet("output_indices","0","batch")};\n ${le.indicesSet("output_indices",ue-1,"col")};\n ${le.indicesSet("output_indices",ue-2,"0")};\n var output_offset = ${le.indicesToOffset("output_indices")};\n for (var m: u32 = 0u; m < ${c}u; m++) {\n var output_value: ${le.type.value} = ${le.type.value}(0);\n var workgroup_shared_offset: u32 = m;\n for (var b: u32 = 0u; b < ${a}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${c};\n }\n ${le.setByOffset("output_offset","output_value")};\n output_offset += ${h/R};\n }\n }\n }`:`\n ${Ce.registerUniforms(qe).declareVariables(...me,le)}\n ${Ce.mainStart()}\n ${Ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var output_values: array<${le.type.value}, ${S}>;\n var output_indices = ${le.offsetToIndices("global_idx")};\n var col = ${le.indicesGet("output_indices",ue-1)};\n var row = ${le.indicesGet("output_indices",ue-2)};\n var a_indices: ${ee.type.indices} = output_indices;\n // Two zero points are packed into one byte because uniforms.bits <= 4.\n // zero_point_offset is either 0 or 4. It is bit offset within one byte.\n // TODO support zero_point_offset for bits > 4\n ${ie?`\n var zero_point_abs_offset = col * ${R} * ((${a} + 1) / 2);\n var zero_point_index: u32 = zero_point_abs_offset / 4;\n var zero_point_word: u32 = ${ie.getByOffset("zero_point_index")};\n var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""}\n var scale_index = col * ${a*R};\n var b_indices: ${ae.type.indices};\n for (var c: u32 = 0; c < ${R}; c++) {\n ${ae.indicesSet("b_indices","0",`col * ${R} + c`)};\n var block_offset: u32 = 0;\n for (var block: u32 = 0; block < ${a}; block++) {\n // The scale and zero points are computed per block.\n let scale = ${Ae.getByOffset("scale_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${G}(${ie?"extractBits(zero_point_word, zero_point_offset, 4)":8});\n ${ae.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block_offset;\n ${xe}\n scale_index++;\n ${Ke}\n block_offset += uniforms.block_size / ${A};\n }\n // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte.\n ${ie?`if (zero_point_offset % 8 > 0) {\n ${Ke}\n }`:""}\n }\n for (var k: u32 = 0u; k < ${S}u; k++) {\n ${le.indicesSet("output_indices",ue-2,`${S} * row + k`)};\n ${le.setByIndices("output_indices","output_values[k]")}\n }\n }`};return{name:O?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${c};${v};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:L,dataType:v}],name:O?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:O?{x:1,y:Math.ceil(h/R),z:y}:{x:Math.ceil(N/64)},programUniforms:K}),getShaderSource:se}},Wu=(e,t)=>{np(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),o=e.getMaxComputeWorkgroupStoragesize();e.compute(op(e.inputs,t,r,o))},Nu=e=>ve(e)});var it,ip,Lu,Hu,ap,Ko,Fu,qu=Y(()=>{"use strict";ye();Se();Ze();_n();Ro();_e();Sr();it=(e,t)=>e.length>t&&e[t].dims.length>0&&M.size(e[t].dims)>0?e[t]:void 0,ip=(e,t)=>{let r=e[0],o=it(e,1),i=it(e,2),u=it(e,3),a=it(e,4),c=it(e,5),p=it(e,6),h=it(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,y=r.dims[0],w=r.dims[1],_=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],v=w,S=0,A=0,I=Math.floor(_/t.numHeads);if(p&&h){if(p.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(p.dims[0]!==y||p.dims[1]!==t.numHeads||p.dims[3]!==I)throw new Error(\'Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(h.dims[0]!==y||h.dims[1]!==t.numHeads||h.dims[3]!==I)throw new Error(\'Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(p.dims[2]!==h.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)\');if(h.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');S=p.dims[2],A=p.dims[2]}else if(p||h)throw new Error(\'Input "past_key" and "past_value" shall be both present or both absent\');let x;if(o){if(r.dims.length!==3)throw new Error(\'Input "query" is expected to have 3 dimensions when key is given\');if(o.dims.length<3||o.dims.length>5)throw new Error(\'Input "key" is expected to have 3, 4, or 5 dimensions\');if(r.dims[0]!==o.dims[0])throw new Error(\'Input "query" and "key" shall have same dim 0 (batch size)\');if(o.dims.length===3){if(o.dims[2]!==r.dims[2])throw new Error(\'Input "query" and "key" shall have same dim 2 (hidden_size)\');x=2,v=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==I)throw new Error(\'Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv\');if(i)throw new Error(\'Expect "value" be none when "key" has packed kv format.\');x=5,v=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==I)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');x=0,v=o.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\'Input "query" is expected to have 3 or 5 dimensions when key is empty\');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error(\'Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv\');x=3}if(u){if(u.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(i&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let E=0;if(a){E=8;let N=a.dims;throw N.length===1?N[0]===y?E=1:N[0]===3*y+2&&(E=3):N.length===2&&N[0]===y&&N[1]===v&&(E=5),E===8?new Error(\'Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)\'):new Error("Mask not supported")}let P=!1,O=_;if(i){if(i.dims.length!==3&&i.dims.length!==4)throw new Error(\'Input "value" is expected to have 3 or 4 dimensions\');if(r.dims[0]!==i.dims[0])throw new Error(\'Input "query" and "value" shall have same dim 0 (batch_size)\');if(i.dims.length===3){if(v!==i.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');O=i.dims[2]}else{if(v!==i.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');O=i.dims[1]*i.dims[3],P=!0}}let R=S+v,L=!1;if(a)throw new Error("Key padding mask is not supported");if(c){if(c.dims.length!==4)throw new Error(\'Input "relative_position_bias" is expected to have 4 dimensions\');if(c.dims[0]!==y&&c.dims[0]!==1||c.dims[1]!==t.numHeads||c.dims[2]!==w||c.dims[3]!==R)throw new Error(\'Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)\')}return{batchSize:y,sequenceLength:w,pastSequenceLength:S,kvSequenceLength:v,totalSequenceLength:R,maxSequenceLength:A,inputHiddenSize:0,hiddenSize:_,vHiddenSize:O,headSize:I,vHeadSize:Math.floor(O/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:E,scale:t.scale,broadcastResPosBias:L,passPastInKv:P,qkvFormat:x}},Lu=e=>ve({...e}),Hu=ve({perm:[0,2,1,3]}),ap=(e,t,r,o,i,u,a)=>{let c=[o,i,u],p=M.size(c),h=[{type:12,data:p},{type:12,data:a},{type:12,data:u}],d=y=>{let w=j("qkv_with_bias",t.dataType,c),_=U("qkv",t.dataType,c),v=U("bias",r.dataType,c),S=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${y.registerUniforms(S).declareVariables(_,v,w)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:d},{inputs:[t,r],outputs:[-1]})[0]},Ko=(e,t,r,o,i,u,a,c)=>{let p=u;if(a){if(o===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=ap(e,u,a,t,o,r*i,c),p=p.reshape([t,o,r,i]),e.compute(yt(p,Hu.perm),{inputs:[p],outputs:[-1]})[0]}else return u.dims.length===3&&(p=u.reshape([t,o,r,i])),e.compute(yt(p,Hu.perm),{inputs:[p],outputs:[-1]})[0]},Fu=(e,t)=>{let r=ip(e.inputs,t),o=e.inputs[0],i=it(e.inputs,1),u=it(e.inputs,2),a=it(e.inputs,3),c=it(e.inputs,4),p=it(e.inputs,5),h=it(e.inputs,6),d=it(e.inputs,7);if(o.dims.length===5)throw new Error("Packed QKV is not implemented");if(i?.dims.length===5)throw new Error("Packed KV is not implemented");let y=i&&u&&i.dims.length===4&&u.dims.length===4,w=Ko(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,o,a,0);if(y)return Pn(e,w,i,u,c,void 0,h,d,p,r,t);if(!i||!u)throw new Error("key and value must be provided");let _=Ko(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,a,r.hiddenSize),v=Ko(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,u,a,2*r.hiddenSize);Pn(e,w,_,v,c,void 0,h,d,p,r,t)}});var sp,up,dp,lp,cp,pp,mp,fp,ju,Ku=Y(()=>{"use strict";ye();Se();_e();sp=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},up=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n break;\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n }\n `},dp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${fe("uniforms.x_shape",i,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},lp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k = i32(${fe("uniforms.x_shape",i,t)}) - 1;\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},cp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k += i32(${fe("uniforms.x_shape",i,t)}]);\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k -= i32(${fe("uniforms.x_shape",i,t)});\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},pp=(e,t,r)=>{switch(r.mode){case 0:return up(e,t,r.pads.length);case 1:return dp(e,t,r.pads.length);case 2:return lp(e,t,r.pads.length);case 3:return cp(e,t,r.pads.length);default:throw new Error("Invalid mode")}},mp=(e,t)=>{let r=M.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,i=M.size(r),u=[{type:12,data:i},{type:6,data:t.pads}];t.mode===0&&u.push({type:e[0].dataType,data:t.value}),u.push(...Z(e[0].dims,r));let a=["rank"],c=p=>{let h=j("output",e[0].dataType,r.length),d=U("x",e[0].dataType,o.length),y=d.type.value,w=pp(h,o.length,t),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&_.push({name:"constant_value",type:y}),`\n ${p.registerUniforms(_).declareVariables(d,h)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${h.offsetToIndices("global_idx")};\n\n var value = ${y}(0);\n ${w}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(M.size(r)/64)},programUniforms:u}),getShaderSource:c}},fp=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),o=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,i=e[0].dims.length,u=new Int32Array(2*i).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let p=0;pu[Number(p)]=Number(c));let a=[];return u.forEach(c=>a.push(c)),{mode:t.mode,value:o,pads:a}}else return t},ju=(e,t)=>{sp(e.inputs);let r=fp(e.inputs,t);e.compute(mp(e.inputs,r),{inputs:[0]})}});var Nn,Yu,Zu,Xu,Qu,hp,gp,Ju,ed,td,rd,nd,od,id,ad,sd,ud,dd,ld,cd=Y(()=>{"use strict";$r();ye();Se();_e();Nn=e=>{if(vr.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Yu=(e,t,r)=>{let o=t.format==="NHWC",i=e.dims.slice();o&&i.splice(1,0,i.pop());let u=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),c=t.strides.slice(),p=u?t.dilations.slice():[],h=t.pads.slice();nr.adjustPoolAttributes(r,i,a,c,p,h);let d=nr.computePoolOutputShape(r,i,c,p,a,h,t.autoPad),y=Object.assign({},t);u?Object.assign(y,{kernelShape:a,strides:c,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(y,{kernelShape:a,strides:c,pads:h,cacheKey:t.cacheKey});let w=d.slice();return w.push(w.splice(1,1)[0]),[y,o?w:d]},Zu=(e,t)=>{let r=t.format==="NHWC",o=M.size(e),i=M.size(t.kernelShape),u=[{type:12,data:o},{type:12,data:i}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],d=t.pads[t.pads.length-1],y=!!(h+d);u.push({type:12,data:c},{type:12,data:p},{type:12,data:h},{type:12,data:d}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let w=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],v=t.strides[t.strides.length-2],S=t.pads[t.pads.length/2-2],A=t.pads[t.pads.length-2];w=!!(S+A),u.push({type:12,data:_},{type:12,data:v},{type:12,data:S},{type:12,data:A}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[u,a,!0,y,w]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=M.computeStrides(t.kernelShape);u.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,d)=>h+d);return[u,a,!!p,!1,!1]}},Xu=(e,t,r,o,i,u,a,c,p,h,d,y)=>{let w=i.format==="NHWC",_=t.type.value,v=j("output",t.type.tensor,o);if(i.kernelShape.length<=2){let S="",A="",I="",x=r-(w?2:1);if(d?S=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${x}] < 0 || xIndices[${x}]\n >= uniforms.x_shape[${x}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n }`:S=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n }`,i.kernelShape.length===2){let P=r-(w?3:2);y?A=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${P}] < 0 || xIndices[${P}] >= uniforms.x_shape[${P}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:A=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;\n `,I=`\n }\n `}return`\n ${e.registerUniforms(p).declareVariables(t,v)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${v.offsetToIndices("global_idx")};\n var xIndices = ${v.offsetToIndices("global_idx")};\n\n var value = ${_}(${c});\n var pad = 0;\n ${A}\n ${S}\n ${I}\n ${a}\n\n output[global_idx] = value;\n }`}else{if(w)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let S=i.kernelShape.length,A=i.pads.length,I="";return h?I=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n }`:I=`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n `,`\n ${e.registerUniforms(p).declareVariables(t,v)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${v.offsetToIndices("global_idx")};\n var xIndices = ${v.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${_}(${c});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${S-1}u; j++) {\n offsets[j] = offset / ${fe("uniforms.kernelStrides","j",S)};\n offset -= offsets[j] * ${fe("uniforms.kernelStrides","j",S)};\n }\n offsets[${S-1}] = offset;\n\n isPad = false;\n for (var j = ${r-S}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${fe("uniforms.strides",`j - ${r-S}u`,S)}\n + offsets[j - ${r-S}u] - ${fe("uniforms.pads","j - 2u",A)};\n ${I}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},Qu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,hp=e=>`${Qu(e)};${e.countIncludePad}`,gp=e=>`${Qu(e)};${e.storageOrder};${e.dilations}`,Ju=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),ed=(e,t,r,o)=>{let[i,u]=Yu(t,o,r),a=U("x",t.dataType,t.dims.length),c=a.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${c}(uniforms.kernelSize);`:h+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[d,y,w,_,v]=Zu(u,i);d.push(...Z(t.dims,u));let S=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${w};${_};${v}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(M.size(u)/64)},programUniforms:d}),getShaderSource:A=>Xu(A,a,t.dims.length,u.length,i,p,h,0,y,w,_,v)}},td=e=>{let t=e.count_include_pad!==0,r=Ju(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let o={countIncludePad:t,...r,cacheKey:""};return{...o,cacheKey:hp(o)}},rd=(e,t)=>{Nn(e.inputs),e.compute(ed("AveragePool",e.inputs[0],!1,t))},nd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},od=e=>{let t=e.format;return{format:t,...nd,cacheKey:t}},id=(e,t)=>{Nn(e.inputs),e.compute(ed("GlobalAveragePool",e.inputs[0],!0,t))},ad=(e,t,r,o)=>{let[i,u]=Yu(t,o,r),a=`\n value = max(x_val, value);\n `,c="",p=U("x",t.dataType,t.dims.length),h=["rank"],[d,y,w,_,v]=Zu(u,i);return d.push(...Z(t.dims,u)),{name:e,shaderCache:{hint:`${o.cacheKey};${w};${_};${v}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(M.size(u)/64)},programUniforms:d}),getShaderSource:S=>Xu(S,p,t.dims.length,u.length,i,a,c,t.dataType===10?-65504:-1e5,y,w,_,v)}},sd=(e,t)=>{Nn(e.inputs),e.compute(ad("MaxPool",e.inputs[0],!1,t))},ud=e=>{let t=e.storage_order,r=e.dilations,o=Ju(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(o.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:r,...o,cacheKey:""};return{...i,cacheKey:gp(i)}},dd=e=>{let t=e.format;return{format:t,...nd,cacheKey:t}},ld=(e,t)=>{Nn(e.inputs),e.compute(ad("GlobalMaxPool",e.inputs[0],!0,t))}});var bp,wp,pd,md=Y(()=>{"use strict";$r();ye();_e();bp=(e,t,r)=>{let o=e===t,i=et&&r>0;if(o||i||u)throw new Error("Range these inputs\' contents are invalid.")},wp=(e,t,r,o)=>{let i=Math.abs(Math.ceil((t-e)/r)),u=[i],a=i,c=[{type:12,data:a},{type:o,data:e},{type:o,data:r},...Z(u)],p=h=>{let d=j("output",o,u.length),y=d.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:y},{name:"delta",type:y}];return`\n ${h.registerUniforms(w).declareVariables(d)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${y}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c})}},pd=e=>{let t=0,r=0,o=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],o=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],o=e.inputs[2].getFloat32Array()[0]),vr.webgpu.validateInputContent&&bp(t,r,o),e.compute(wp(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var vp,$p,_p,Sp,xp,Cp,Ap,Ip,Tp,Ep,Pp,fd,kp,Op,Rp,Bp,Dp,hd,gd,yd=Y(()=>{"use strict";ye();Se();Ze();_e();vp=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},$p=(e,t,r)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let o=new Array(r).fill(1);return t.forEach((i,u)=>o[i]=e[u]),o},_p=(e,t,r,o,i,u)=>{let[a,c,p]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(d=>u.push(d));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length>0){if(e[c].getFloat32Array().forEach(d=>o.push(d)),o.length!==0&&o.length!==h&&r>=18&&o.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");vp(o,t),t.axes.length>0&&$p(o,t.axes,h).forEach((d,y)=>o[y]=d)}if(p>0&&e.length>p&&(e[p].getBigInt64Array().forEach(d=>i.push(Number(d))),i.length!==h||r>=18&&i.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(o.length!==t.axes.length)throw new Error(\'Resize requires "scales" input size to be of axes rank when axes attributes is specified\');if(i.length!==t.axes.length)throw new Error(\'Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified\')}if(typeof o<"u"&&typeof i<"u"&&o.length>0&&i.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Sp=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",xp=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Cp=(e,t,r)=>{let o=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?o:e.slice();return t.length>0?(t.forEach((u,a)=>{o[u]=i[a],o[a+r]=i[t.length+a]}),o):i},Ap=(e,t,r,o)=>{let i=[];if(r.length>0)if(o.length>0){if(e.forEach(u=>i.push(u)),Math.max(...o)>e.length)throw new Error("axes is out of bound");o.forEach((u,a)=>i[u]=r[a])}else r.forEach(u=>i.push(u));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((u,a)=>Math.round(u*t[a]))}return i},Ip=(e,t,r)=>{let o=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(u=>t[u]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(u=>t[u]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return r.axes.length>0?(r.axes.forEach(u=>t[u]=o),r.axes.forEach(u=>i[u]=Math.round(e[u]*t[u]))):(t.fill(o,0,t.length),i.forEach((u,a)=>i[a]=Math.round(u*t[a]))),i},Tp=(e,t,r,o,i)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${fe("uniforms.scales","i",o)};\n var roi_low = ${fe("uniforms.roi","i",i)};\n var roi_hi = ${fe("uniforms.roi",`i + ${t.length}`,i)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${fe("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${fe("uniforms.output_shape","i",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Ep=(e,t,r,o,i,u,a)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${o.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${fe("uniforms.scales","i",i)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${fe("uniforms.roi","i",u)};\n var roi_hi = ${fe("uniforms.roi",`i + ${r.length}`,u)};\n var input_shape_i = ${fe("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${fe("uniforms.output_shape","i",o.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,Pp=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${fe("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,fd=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",kp=(e,t,r,o,i)=>{let[a,c,p,h]=r.length===2?[-1,0,1,-1]:[0,2,3,1],d=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${d} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",c,`max(0, min(row, ${r[c]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(col, ${r[p]} - 1))`)};\n ${fd(e,h,a,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${d} = originalIndices[${c}];\n var col:${d} = originalIndices[${p}];\n ${o?`if (row < 0 || row > (${r[c]} - 1) || col < 0 || col > (${r[p]} - 1)) {\n return ${i};\n }`:""};\n row = max(0, min(row, ${r[c]} - 1));\n col = max(0, min(col, ${r[p]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${h}])`:"0"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"};\n var x11: ${d} = getInputValue(batch, channel, row1, col1);\n var x12: ${d} = getInputValue(batch, channel, row1, col2);\n var x21: ${d} = getInputValue(batch, channel, row2, col1);\n var x22: ${d} = getInputValue(batch, channel, row2, col2);\n var dx1: ${d} = abs(row - ${d}(row1));\n var dx2: ${d} = abs(${d}(row2) - row);\n var dy1: ${d} = abs(col - ${d}(col1));\n var dy2: ${d} = abs(${d}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Op=(e,t,r,o,i,u,a,c,p,h)=>{let d=r.length===2,y=!0,[w,_]=d?[0,1]:y?[2,3]:[1,2],v=e.type.value,S=A=>{let I=A===w?"row":"col";return`\n fn ${I}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${v} {\n var output_index = ${t.indicesGet("output_indices",A)};\n var originalIdx: ${v} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[A]},\n ${o[A]}, ${r[A]}, ${u[A]}, ${u[A]} + ${r.length});\n var fractOriginalIdx: ${v} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${c} && (originalIdx < 0 || originalIdx > (${r[A]} - 1))) {\n return ${p};\n }\n var data: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${I}: ${v} = originalIdx + ${v}(i);\n if (${I} < 0 || ${I} >= ${r[A]}) {\n ${(()=>h?`coefs[i + 1] = 0.0;\n continue;`:c?`return ${p};`:`${I} = max(0, min(${I}, ${r[A]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",A,`u32(${I})`)};\n data[i + 1] = ${A===w?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${S(w)};\n ${S(_)};\n fn getCubicInterpolationCoefs(s: ${v}) -> array<${v}, 4> {\n var absS = abs(s);\n var coeffs: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${v} = 1.0 - absS;\n var twoMinusAbsS: ${v} = 2.0 - absS;\n var onePlusAbsS: ${v} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${v}, 4>, coefs: array<${v}, 4>) -> ${v} {\n var coefsSum: ${v} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${v} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Rp=(e,t,r,o,i)=>{let[a,c,p,h,d]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],y=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${y} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",c,`max(0, min(depth, ${r[c]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(height, ${r[p]} - 1))`)};\n ${e.indicesSet("input_indices",h,`max(0, min(width, ${r[h]} - 1))`)};\n ${fd(e,d,a,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${y} = originalIndices[${c}];\n var height:${y} = originalIndices[${p}];\n var width:${y} = originalIndices[${h}];\n ${o?`if (depth < 0 || depth > (${r[c]} - 1) || height < 0 || height > (${r[p]} - 1) || width < 0 || (width > ${r[h]} - 1)) {\n return ${i};\n }`:""};\n\n depth = max(0, min(depth, ${r[c]} - 1));\n height = max(0, min(height, ${r[p]} - 1));\n width = max(0, min(width, ${r[h]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${d}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"};\n\n var x111: ${y} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${y} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${y} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${y} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${y} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${y} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${y} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${y} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${y} = abs(depth - ${y}(depth1));\n var dx2: ${y} = abs(${y}(depth2) - depth);\n var dy1: ${y} = abs(height - ${y}(height1));\n var dy2: ${y} = abs(${y}(height2) - height);\n var dz1: ${y} = abs(width - ${y}(width1));\n var dz2: ${y} = abs(${y}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Bp=(e,t,r,o,i,u)=>{let a=e.dims,c=Cp(u,t.axes,a.length),p=Ap(a,o,i,t.axes),h=o.slice();o.length===0&&(h=a.map((x,E)=>x===0?1:p[E]/x),t.keepAspectRatioPolicy!=="stretch"&&(p=Ip(a,h,t)));let d=j("output",e.dataType,p.length),y=U("input",e.dataType,a.length),w=M.size(p),_=a.length===p.length&&a.every((x,E)=>x===p[E]),v=t.coordinateTransformMode==="tf_crop_and_resize",S=t.extrapolationValue,A=y.type.value,I=x=>`\n ${_?"":`\n ${Sp(t.coordinateTransformMode,A)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Pp(y,a)};\n ${xp(t.nearestMode,r,A)};\n ${Ep(y,d,a,p,h.length,c.length,v)};\n `;case"linear":return`\n ${Tp(d,a,p,h.length,c.length)};\n ${(()=>{if(a.length===2||a.length===4)return`${kp(y,d,a,v,S)}`;if(a.length===3||a.length===5)return`${Rp(y,d,a,v,S)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(a.length===2||a.length===4)return`${Op(y,d,a,p,h,c,t.cubicCoeffA,v,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${x.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",c.length).declareVariables(y,d)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${_?"output[global_idx] = input[global_idx];":`\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${y.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${y.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${h.length>0?h:""}|${i.length>0?i:""}|${c.length>0?c:""}|${_}|${a}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:h},{type:1,data:c},...Z(a,p)]})}},Dp=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},hd=(e,t)=>{let r=[],o=[],i=[],u=Dp(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");_p(e.inputs,t,u,r,o,i),e.compute(Bp(e.inputs[0],t,u,r,o,i),{inputs:[0]})},gd=e=>{let t=e.antialias,r=e.axes,o=e.coordinateTransformMode,i=e.cubicCoeffA,u=e.excludeOutside!==0,a=e.extrapolationValue,c=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return ve({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:i,excludeOutside:u,extrapolationValue:a,keepAspectRatioPolicy:c,mode:p,nearestMode:h})}});var zp,Mp,bd,wd=Y(()=>{"use strict";ye();Se();Ze();_e();zp=(e,t)=>{let[r,o,i,u]=e,{numHeads:a,rotaryEmbeddingDim:c}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input \'x\' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!M.areEqual(o.dims,[])&&!M.areEqual(o.dims,[1])&&o.dims.length!==2)throw new Error(`Input \'position_ids\' is expected to have 0, 1, or 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input \'cos_cache\' is expected to have 2 dimensions, got ${i.dims.length}`);if(u.dims.length!==2)throw new Error(`Input \'sin_cache\' is expected to have 2 dimensions, got ${u.dims.length}`);if(!M.areEqual(i.dims,u.dims))throw new Error("Inputs \'cos_cache\' and \'sin_cache\' are expected to have the same shape");if(c>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=r.dims[0],h=r.dims[r.dims.length-2],d=i.dims[0],y=M.sizeFromDimension(r.dims,1)/h,w=c===0?i.dims[1]*2:y/a;if(c>w)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(o.dims.length===2){if(p!==o.dims[0])throw new Error(`Input \'position_ids\' dimension 0 should be of size batch_size, got ${o.dims[0]}`);if(h!==o.dims[1])throw new Error(`Input \'position_ids\' dimension 1 should be of size sequence_length, got ${o.dims[1]}`)}if(w/2!==i.dims[1]&&c/2!==i.dims[1])throw new Error(`Input \'cos_cache\' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>d)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Mp=(e,t)=>{let{interleaved:r,numHeads:o,rotaryEmbeddingDim:i,scale:u}=t,a=e[0].dims[0],c=M.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=c/p,d=e[2].dims[1],y=i===0?d*2:h/o,w=new Array(a,p,h/y,y-d),_=M.computeStrides(w),v=[{type:1,data:u},{type:12,data:w},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[c,h,y,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,y,p*y,1]}):[],...Z(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],S=A=>{let I=U("input",e[0].dataType,e[0].dims.length),x=U("position_ids",e[1].dataType,e[1].dims.length),E=U("cos_cache",e[2].dataType,e[2].dims.length),P=U("sin_cache",e[3].dataType,e[3].dims.length),O=j("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),`\n ${A.declareVariables(I,x,E,P,O)}\n\n ${A.mainStart(or)}\n let half_rotary_emb_dim = uniforms.${E.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${x.broadcastedIndicesToOffset("bsnh.xy",j("",x.type.tensor,2))};\n let position_id =\n u32(${x.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});\n let j = i + select(half_rotary_emb_dim, 1, ${r});\n let re = ${I.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} -\n ${I.getByOffset("j")} * ${P.get("position_id","bsnh[3]")};\n ${O.setByOffset("i","re")}\n let im = ${I.getByOffset("i")} * ${P.get("position_id","bsnh[3]")} +\n ${I.getByOffset("j")} * ${E.get("position_id","bsnh[3]")};\n ${O.setByOffset("j","im")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${O.setByOffset("k",I.getByOffset("k"))}\n }\n }`};return{name:"RotaryEmbedding",shaderCache:{hint:ve({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:S,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(M.size(w)/or)},programUniforms:v})}},bd=(e,t)=>{zp(e.inputs,t),e.compute(Mp(e.inputs,t))}});var Up,Vp,vd,$d=Y(()=>{"use strict";ye();Se();_e();Up=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],o=e[2];if(t.dataType!==r.dataType||t.dataType!==o.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],u=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==u)throw new Error("Skip must have the same sequence length as input");if(o.dims.length!==1)throw new Error("Gamma must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Vp=(e,t,r,o)=>{let i=t.simplified,u=e[0].dims,a=M.size(u),c=u,p=a,h=u.slice(-1)[0],d=o?u.slice(0,-1).concat(1):[],y=!i&&e.length>3,w=e.length>4,_=o&&r>1,v=o&&r>2,S=r>3,A=Me(h),I=[{type:12,data:p},{type:12,data:A},{type:12,data:h},{type:1,data:t.epsilon}],x=P=>{let O=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],R=[U("x",e[0].dataType,e[0].dims,A),U("skip",e[1].dataType,e[1].dims,A),U("gamma",e[2].dataType,e[2].dims,A)];y&&R.push(U("beta",e[3].dataType,e[3].dims,A)),w&&R.push(U("bias",e[4].dataType,e[4].dims,A)),R.push(j("output",e[0].dataType,c,A)),_&&R.push(j("mean_output",1,d)),v&&R.push(j("inv_std_output",1,d)),S&&R.push(j("input_skip_bias_sum",e[0].dataType,c,A));let L=De(e[0].dataType);return`\n\n ${P.registerUniforms(O).declareVariables(...R)}\n\n ${P.mainStart()}\n ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")}\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n let offset = global_idx * hidden_size_vectorized;\n var sum = ${$t("f32",A)};\n var squareSum = ${$t("f32",A)};\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${w?"bias[i]":L+"(0.0)"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${S?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${ir(L,A,"value")};\n sum += f32_value;\n squareSum += f32_value * f32_value;\n }\n let mean = ${_t("sum",A)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${_t("squareSum",A)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon);\n ${_?"mean_output[global_idx] = mean;":""}\n ${v?"inv_std_output[global_idx] = inv_std_dev;":""}\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n output[offset + i] = (output[offset + i] ${i?"":`- ${L}(mean)`}) * ${L}(inv_std_dev) * gamma[i] ${y?"+ beta[i]":""};\n }\n }`},E=[{dims:c,dataType:e[0].dataType}];return r>1&&E.push({dims:d,dataType:1}),r>2&&E.push({dims:d,dataType:1}),r>3&&E.push({dims:u,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${A};${_};${v};${S}`,inputDependencies:e.map((P,O)=>"type")},getShaderSource:x,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(p/h/64)},programUniforms:I})}},vd=(e,t)=>{Up(e.inputs);let o=[0];e.outputCount>1&&o.push(-3),e.outputCount>2&&o.push(-3),e.outputCount>3&&o.push(3),e.compute(Vp(e.inputs,t,e.outputCount,!1),{outputs:o})}});var Wp,Gn,Np,_d,Gp,Hp,Sd,xd,Cd=Y(()=>{"use strict";ye();Se();Ze();_e();Wp=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,o)=>{if(e[o+1].dataType!==6&&e[o+1].dataType!==7)throw new Error(`Input ${o} must be an array of int32 or int64`)})},Gn=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(o=>r.push(Number(o)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(o=>r.push(Number(o)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Np=(e,t)=>{if(e.length>1){let r=Gn(e,1),o=Gn(e,2),i=Gn(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),ve({starts:r,ends:o,axes:i})}else return t},_d=(e,t,r,o,i)=>{let u=e;return e<0&&(u+=r[o[t]]),i[t]<0?Math.max(0,Math.min(u,r[o[t]]-1)):Math.max(0,Math.min(u,r[o[t]]))},Gp=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${fe("uniforms.input_shape","i",r.length)};\n let steps_i = ${fe("uniforms.steps","i",r.length)};\n let signs_i = ${fe("uniforms.signs","i",r.length)};\n let starts_i = ${fe("uniforms.starts","i",r.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,Hp=(e,t)=>{let r=e[0].dims,o=M.size(r),i=t.axes.length>0?M.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],u=Gn(e,4);u.forEach(I=>I!==0||(()=>{throw new Error("step cannot be 0")})),u.length===0&&(u=Array(i.length).fill(1));let a=t.starts.map((I,x)=>_d(I,x,r,i,u)),c=t.ends.map((I,x)=>_d(I,x,r,i,u));if(i.length!==a.length||i.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let I=0;IMath.sign(I));u.forEach((I,x,E)=>{if(I<0){let P=(c[x]-a[x])/I,O=a[x],R=O+P*u[x];a[x]=R,c[x]=O,E[x]=-I}});let h=r.slice(0);i.forEach((I,x)=>{h[I]=Math.ceil((c[I]-a[I])/u[I])});let d={dims:h,dataType:e[0].dataType},y=j("output",e[0].dataType,h.length),w=U("input",e[0].dataType,e[0].dims.length),_=M.size(h),v=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:u.length}],S=[{type:12,data:_},{type:12,data:a},{type:6,data:p},{type:12,data:u},...Z(e[0].dims,h)],A=I=>`\n ${I.registerUniforms(v).declareVariables(w,y)}\n ${Gp(w,y,r)}\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${y.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${y.setByOffset("global_idx",w.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${a.length}_${u.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:S})}},Sd=(e,t)=>{Wp(e.inputs,t);let r=Np(e.inputs,t);e.compute(Hp(e.inputs,r),{inputs:[0]})},xd=e=>{let t=e.starts,r=e.ends,o=e.axes;return ve({starts:t,ends:r,axes:o})}});var Lp,Fp,Ad,Id,Td=Y(()=>{"use strict";ye();Se();Ze();_e();Lp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Fp=(e,t)=>{let r=e.dims,o=M.size(r),i=64,u=t.axis;if(u<0&&(u=r.length+u),uI===4?`max(max(${A}.x, ${A}.y), max(${A}.z, ${A}.w))`:I===2?`max(${A}.x, ${A}.y)`:I===3?`max(max(${A}.x, ${A}.y), ${A}.z)`:A,y=U("x",e.dataType,e.dims,p),w=j("result",e.dataType,e.dims,p),_=y.type.value,v=De(e.dataType)==="f32"?`var threadMax = ${_}(-3.402823e+38f);`:`var threadMax = ${_}(-65504.0h);`,S=A=>`\n var rowMaxShared : ${_};\n var rowSumShared : ${_};\n var threadShared : array<${_}, ${i}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${_} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${_}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${A.registerUniform("packedCols","i32").declareVariables(y,w)}\n ${A.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${i};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${v}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${_}(${d("threadShared[0]",p)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${_}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${_}(${_t("threadShared[0]",p)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`;return{name:"Softmax",shaderCache:{hint:`${p}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:h}]}),getShaderSource:S}},Ad=(e,t)=>{Lp(e.inputs),e.compute(Fp(e.inputs[0],t))},Id=e=>ve({axis:e.axis})});var qp,jp,Kp,Yp,Zp,Ed,Pd,kd=Y(()=>{"use strict";ye();Se();Ze();_e();qp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},jp=(e,t)=>{let r=[],o=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),o=r.length),ve({numOutputs:o,axis:t.axis,splitSizes:r})},Kp=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${fe("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Yp=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=M.size(r),i=e[0].dataType,u=M.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),c=U("input",i,r.length),p=new Array(t.numOutputs),h=[],d=[],y=0,w=[{type:12,data:o}];for(let v=0;v`\n ${v.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(c,...a)}\n ${Kp(p.length)}\n ${Yp(a)}\n\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${c.offsetToIndices("global_idx")};\n var index = ${c.indicesGet("indices",u)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${fe("uniforms.size_in_split_axis","output_number - 1u",p.length)};\n ${c.indicesSet("indices",u,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:w})}},Ed=(e,t)=>{qp(e.inputs);let r=e.inputs.length===1?t:jp(e.inputs,t);e.compute(Zp(e.inputs,r),{inputs:[0]})},Pd=e=>{let t=e.axis,r=e.splitSizes,o=e.numOutputs<0?r.length:e.numOutputs;if(o!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ve({axis:t,numOutputs:o,splitSizes:r})}});var Od,Xp,Qp,Jp,Rd,Bd=Y(()=>{"use strict";ye();Se();_e();Od=e=>Array.from(e.getBigInt64Array(),Number),Xp=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Od(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Qp=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=Od(e[1]),o=Qp(t,r),i=M.size(o),u=e[0].dataType,a=U("input",u,t.length),c=j("output",u,o.length),p=h=>`\n const inputShape = ${a.indices(...t)};\n ${h.registerUniform("output_size","u32").declareVariables(a,c)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${c.offsetToIndices("global_idx")};\n var input_indices: ${a.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${c.indicesGet("output_indices","i")} % input_dim_i;\n\n ${a.indicesSet("input_indices","i","input_dim_value")}\n }\n ${c.setByOffset("global_idx",a.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...Z(e[0].dims,o)]}),getShaderSource:p}},Rd=e=>{Xp(e.inputs),e.compute(Jp(e.inputs),{inputs:[0]})}});var em,tm,Dd,zd=Y(()=>{"use strict";ye();Se();_e();em=(e,t,r,o,i)=>{let u=j("output_data",i,r.length,4),a=U("a_data",t[1].dataType,t[1].dims.length,4),c=U("b_data",t[2].dataType,t[2].dims.length,4),p=U("c_data",t[0].dataType,t[0].dims.length,4),h,d=(y,w,_)=>`select(${w}, ${y}, ${_})`;if(!o)h=u.setByOffset("global_idx",d(a.getByOffset("global_idx"),c.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let y=(w,_,v="")=>{let S=`a_data[index_a${_}][component_a${_}]`,A=`b_data[index_b${_}][component_b${_}]`,I=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`\n let output_indices${_} = ${u.offsetToIndices(`global_idx * 4u + ${_}u`)};\n let offset_a${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let offset_b${_} = ${c.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let offset_c${_} = ${p.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let index_a${_} = offset_a${_} / 4u;\n let index_b${_} = offset_b${_} / 4u;\n let index_c${_} = offset_c${_} / 4u;\n let component_a${_} = offset_a${_} % 4u;\n let component_b${_} = offset_b${_} % 4u;\n let component_c${_} = offset_c${_} % 4u;\n ${w}[${_}] = ${v}(${d(S,A,I)});\n `};i===9?h=`\n var data = vec4(0);\n ${y("data",0,"u32")}\n ${y("data",1,"u32")}\n ${y("data",2,"u32")}\n ${y("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=`\n ${y("output_data[global_idx]",0)}\n ${y("output_data[global_idx]",1)}\n ${y("output_data[global_idx]",2)}\n ${y("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(p,a,c,u)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${h}\n }`},tm=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,i=e[1].dataType,u=!(M.areEqual(t,r)&&M.areEqual(r,o)),a=t,c=M.size(t);if(u){let h=It.calcShape(It.calcShape(t,r,!1),o,!1);if(!h)throw new Error("Can\'t perform where op on the given tensors");a=h,c=M.size(a)}let p=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>em(h,e,a,u,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:p},...Z(o,t,r,a)]})}},Dd=e=>{e.compute(tm(e.inputs))}});var Md,Ud=Y(()=>{"use strict";Ka();Ro();Ja();ts();Vs();Zs();Oo();Uo();lu();mu();gu();$u();xu();Au();Eu();Ou();Du();Mu();Vu();Wo();Gu();qu();Ku();cd();md();In();yd();wd();$d();Cd();Td();kd();Bd();Sr();Rn();zd();Md=new Map([["Abs",[rs]],["Acos",[ns]],["Acosh",[os]],["Add",[Ws]],["ArgMax",[ja,ko]],["ArgMin",[qa,ko]],["Asin",[is]],["Asinh",[as]],["Atan",[ss]],["Atanh",[us]],["Attention",[Xa]],["AveragePool",[rd,td]],["BatchNormalization",[Qa]],["BiasAdd",[es]],["BiasSplitGelu",[Us]],["Cast",[ls,ds]],["Ceil",[ps]],["Clip",[cs]],["Concat",[Ya,Za]],["Conv",[Ho,Go]],["ConvTranspose",[du,uu]],["Cos",[ms]],["Cosh",[fs]],["CumSum",[cu,pu]],["DepthToSpace",[fu,hu]],["Div",[Ns]],["Einsum",[wu,vu]],["Elu",[hs,kn]],["Equal",[Gs]],["Erf",[gs]],["Exp",[ys]],["Expand",[Su]],["FastGelu",[Cu]],["Floor",[bs]],["FusedConv",[Ho,Go]],["Gather",[Tu,Iu]],["GatherElements",[ku,Pu]],["Gelu",[ws]],["Gemm",[Bu,Ru]],["GlobalAveragePool",[id,od]],["GlobalMaxPool",[ld,dd]],["Greater",[qs]],["GreaterOrEqual",[Ks]],["HardSigmoid",[Is,As]],["InstanceNormalization",[zu]],["LayerNormalization",[Uu]],["LeakyRelu",[vs,kn]],["Less",[js]],["LessOrEqual",[Ys]],["Log",[zs]],["MatMul",[ru]],["MatMulNBits",[Wu,Nu]],["MaxPool",[sd,ud]],["Mul",[Hs]],["MultiHeadAttention",[Fu,Lu]],["Neg",[_s]],["Not",[$s]],["Pad",[ju]],["Pow",[Ls]],["Range",[pd]],["Reciprocal",[Ss]],["ReduceMin",[Wa]],["ReduceMean",[Da]],["ReduceMax",[Va]],["ReduceSum",[Ga]],["ReduceProd",[Na]],["ReduceL1",[za]],["ReduceL2",[Ma]],["ReduceLogSum",[La]],["ReduceLogSumExp",[Ua]],["ReduceSumSquare",[Ha]],["Relu",[xs]],["Resize",[hd,gd]],["RotaryEmbedding",[bd]],["Sigmoid",[Cs]],["Sin",[Ts]],["Sinh",[Es]],["Slice",[Sd,xd]],["SkipLayerNormalization",[vd]],["Split",[Ed,Pd]],["Sqrt",[Ps]],["Softmax",[Ad,Id]],["Sub",[Fs]],["Tan",[ks]],["Tanh",[Rs]],["ThresholdedRelu",[Ds,kn]],["Tile",[Rd]],["Transpose",[_a,Sa]],["Where",[Dd]]])});var Hn,Vd=Y(()=>{"use strict";$r();Lt();_e();Hn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,o,i,u){rr(t.programInfo.name);let a=this.backend.device,c=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let p=[];for(let d of r)p.push({binding:p.length,resource:{buffer:d.buffer}});for(let d of o)p.push({binding:p.length,resource:{buffer:d.buffer}});u&&p.push({binding:p.length,resource:u});let h=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:p,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:h,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}c.setPipeline(t.computePipeline),c.setBindGroup(0,h),c.dispatchWorkgroups(...i),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ht(t.programInfo.name)}dispose(){}build(t,r){rr(t.name);let o=this.backend.device,i=[];o.features.has("shader-f16")&&i.push("enable f16;");let u=va(r,this.backend.device.limits),a=t.getShaderSource(u),c=`${i.join(`\n`)}\n${u.additionalImplementations}\n${a}`,p=o.createShaderModule({code:c,label:t.name});Ve("verbose",()=>`[WebGPU] ${t.name} shader code: ${c}`);let h=o.createComputePipeline({compute:{module:p,entryPoint:"main"},layout:"auto",label:t.name});return Ht(t.name),{programInfo:t,computePipeline:h,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,o=typeof t=="number"?1:t.y||1,i=typeof t=="number"?1:t.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=u&&o<=u&&i<=u)return[r,o,i];let a=r*o*i,c=Math.ceil(Math.sqrt(a));if(c>u){if(c=Math.ceil(Math.cbrt(a)),c>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[c,c,c]}else return[c,c,1]}}});var rm,nm,Yo,Ln,Wd=Y(()=>{"use strict";$r();ye();Lt();fa();wa();Ud();Vd();rm=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let o=0;o{let o=e.name;return e.shaderCache?.hint&&(o+="["+e.shaderCache.hint+"]"),o+=":"+r+`:${rm(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},Yo=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Ln=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let o=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:o};r.features.has("chromium-experimental-timestamp-query-inside-passes")?o.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&o.push("timestamp-query"),r.features.has("shader-f16")&&o.push("shader-f16"),this.device=await r.requestDevice(i),this.adapterInfo=new Yo(await r.requestAdapterInfo()),this.gpuDataManager=ba(this),this.programManager=new Hn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,pa(t.logLevel,!!t.debug),this.device.onuncapturederror=u=>{u.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${u.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;rr(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),o=this.pendingQueries.get(t);for(let i=0;i"u"&&(this.queryTimeBase=_);let S=Number(_-this.queryTimeBase),A=Number(v-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:y.map(I=>({dims:I.dims,dataType:Gt(I.dataType)})),outputsMetadata:w.map(I=>({dims:I.dims,dataType:Gt(I.dataType)})),kernelId:a,kernelType:p,kernelName:h,programName:d,startTime:S,endTime:A});else{let I="";y.forEach((E,P)=>{I+=`input[${P}]: [${E.dims}] | ${Gt(E.dataType)}, `});let x="";w.forEach((E,P)=>{x+=`output[${P}]: [${E.dims}] | ${Gt(E.dataType)}, `}),console.log(`[profiling] kernel "${a}|${p}|${h}|${d}" ${I}${x}execution time: ${A-S} ns`)}wo("GPU",`${d}::${_}::${v}`)}t.unmap(),this.pendingQueries.delete(t)}),Ht()}run(t,r,o,i,u,a){rr(t.name);let c=[];for(let E=0;EP):o;if(y.length!==p.length)throw new Error(`Output size ${y.length} must be equal to ${p.length}.`);let w=[],_=[];for(let E=0;E=a)throw new Error(`Invalid output index: ${y[E]}`);if(y[E]===-3)continue;let P=y[E]===-1,O=y[E]===-2,R=P||O?u(p[E].dataType,p[E].dims):i(y[E],p[E].dataType,p[E].dims);if(w.push(R),R.data===0)continue;let L=this.gpuDataManager.get(R.data);if(!L)throw new Error(`no GPU data for output: ${R.data}`);if(P&&this.temporaryData.push(L),O){let N=this.kernelPersistentData.get(this.currentKernelId);N||(N=[],this.kernelPersistentData.set(this.currentKernelId,N)),N.push(L)}_.push(L)}if(c.length!==r.length||_.length!==w.length){if(_.length===0)return Ht(t.name),w;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let v;if(d){let E=0,P=[];d.forEach(N=>{let K=typeof N.data=="number"?[N.data]:N.data;if(K.length===0)return;let Q=N.type===10?2:4,he,W;N.type===10?(W=K.length>4?16:K.length>2?8:K.length*Q,he=K.length>4?16:Q*K.length):(W=K.length<=2?K.length*Q:16,he=16),E=Math.ceil(E/W)*W,P.push(E);let se=N.type===10?8:4;E+=K.length>4?Math.ceil(K.length/se)*he:K.length*Q});let O=16;E=Math.ceil(E/O)*O;let R=new ArrayBuffer(E);d.forEach((N,K)=>{let Q=P[K],he=typeof N.data=="number"?[N.data]:N.data;if(N.type===6)new Int32Array(R,Q,he.length).set(he);else if(N.type===12)new Uint32Array(R,Q,he.length).set(he);else if(N.type===10)new Uint16Array(R,Q,he.length).set(he);else if(N.type===1)new Float32Array(R,Q,he.length).set(he);else throw new Error(`Unsupported uniform type: ${Gt(N.type)}`)});let L=this.gpuDataManager.create(E,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(L.buffer,0,R,0,E),this.gpuDataManager.release(L.id),v={offset:0,size:E,buffer:L.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),A=S[1]===1&&S[2]===1,I=nm(t,r,A),x=this.programManager.getArtifact(I);if(x||(x=this.programManager.build(t,S),this.programManager.setArtifact(I,x),Ve("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),d&&x.uniformVariablesInfo){if(d.length!==x.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${x.uniformVariablesInfo.length}, got ${d.length} in program "${x.programInfo.name}".`);for(let E=0;E`[ProgramManager] run "${t.name}" (key=${I}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let E={kernelId:this.currentKernelId,programName:x.programInfo.name,inputTensorViews:r,outputTensorViews:w};this.pendingKernels.push(E),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(E)}return this.programManager.run(x,c,_,S,v),Ht(t.name),w}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,o,i){let u=Md.get(t);if(!u)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:i,kernelEntry:u[0],attributes:[u[1],o]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let o of r)this.gpuDataManager.release(o.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,o){let i=this.kernels.get(t);if(!i)throw new Error(`kernel not created: ${t}`);let u=i.kernelType,a=i.kernelName,c=i.kernelEntry,p=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${a}" is not allowed to be called recursively`);this.currentKernelId=t,p[0]&&(p[1]=p[0](p[1]),p[0]=void 0),Ve("info",()=>`[WebGPU] Start to run kernel "[${u}] ${a}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),c(r,p[1]),0}catch(d){return o.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${a}" failed. ${d}`)),1}finally{h&&o.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${u}] ${a}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,o,i){let u=this.sessionExternalDataMapping.get(t);u||(u=new Map,this.sessionExternalDataMapping.set(t,u));let a=u.get(r),c=this.gpuDataManager.registerExternalBuffer(o,i,a?.[1]);return u.set(r,[c,o]),c}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(o=>this.gpuDataManager.unregisterExternalBuffer(o[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,o){return async()=>{let i=await xo(this,t,r);return ma(i.buffer,o)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Ve("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Ve("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ve("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),o=t.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var Nd={};gn(Nd,{init:()=>om});var qr,Zo,om,Gd=Y(()=>{"use strict";ye();Wd();Lt();Se();qr=class e{constructor(t,r,o,i){this.module=t;this.dataType=r;this.data=o;this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=M.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=M.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=M.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(M.size(t)!==M.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Zo=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let i=t.HEAPU32,u=o>>>2;this.opKernelContext=i[u++];let a=i[u++];this.outputCount=i[u++],this.customDataOffset=i[u++],this.customDataSize=i[u++];let c=[];for(let p=0;ptypeof c=="number"?this.inputs[c]:c)??this.inputs,i=r?.outputs??[],u=(c,p,h)=>new qr(this.module,p,this.output(c,h),h),a=(c,p)=>{let h=tr(c);if(!h)throw new Error(`Unsupported data type: ${c}`);let d=h*M.size(p),y=d>0?this.backend.gpuDataManager.create(d).id:0;return new qr(this.module,c,y,p)};return this.backend.run(t,o,i,u,a,this.outputCount)}output(t,r){let o=this.module.stackSave();try{let i=this.module.stackAlloc((1+r.length)*4),u=i>>2;this.module.HEAPU32[u++]=r.length;for(let a=0;a{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let u=new Ln;await u.initialize(r,o),i("webgpu",[u,a=>u.alloc(a),a=>u.free(a),(a,c,p,h=!1)=>{if(h)Ve("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${c}, size=${p}`),u.memcpy(a,c);else{Ve("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${c}, size=${p}`);let d=t.HEAPU8.subarray(a>>>0,(a>>>0)+p);u.upload(c,d)}},async(a,c,p)=>{Ve("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${c}, size=${p}`),await u.download(a,()=>t.HEAPU8.subarray(c>>>0,(c>>>0)+p))},(a,c,p)=>u.createKernel(a,c,p,t.UTF8ToString(t._JsepGetNodeName(c))),a=>u.releaseKernel(a),(a,c,p,h)=>{Ve("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${a}, contextDataOffset=${c}`);let d=new Zo(t,u,c);return u.computeKernel(a,d,h)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else i("webnn")}});var Vi;Vi=Ei();var pl=zi(),fo,ho=!1,yn=!1,Ui=!1,ml=e=>{if(e===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},fl=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},hl=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Wi=async e=>{if(ho)return Promise.resolve();if(yn)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Ui)throw new Error("previous call to \'initializeWebAssembly()\' failed.");yn=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,i=ml(r),u=o&&fl(),a=e.wasmPaths,c=typeof a=="string"?a:void 0,p=hl(u,i),h=typeof a=="object"?a[p]:void 0,d=!1,y=[];if(t>0&&y.push(new Promise(w=>{setTimeout(()=>{d=!0,w()},t)})),y.push(new Promise((w,_)=>{let v=i?pl:Vi,S={locateFile:(A,I)=>{if(i&&A.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Mi()],{type:"text/javascript"}));if(A.endsWith(".wasm")){if(h)return h;let x=c??I;return p==="ort-wasm-simd.wasm"?x+"ort-wasm-simd.jsep.wasm":p==="ort-wasm-simd-threaded.wasm"?x+"ort-wasm-simd-threaded.jsep.wasm":x+p}return I+A}};if(i)if(S.numThreads=r,typeof Blob>"u")S.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let A=`var ortWasmThreaded=${v.toString()};`;S.mainScriptUrlOrBlob=new Blob([A],{type:"text/javascript"})}v(S).then(A=>{yn=!1,ho=!0,fo=A,w()},A=>{yn=!1,Ui=!0,_(A)})})),await Promise.race(y),d)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Le=()=>{if(ho&&fo)return fo;throw new Error("WebAssembly is not initialized yet.")};var Fe=(e,t)=>{let r=Le(),o=r.lengthBytesUTF8(e)+1,i=r._malloc(o);return r.stringToUTF8(e,i,o),t.push(i),i},Nr=(e,t,r,o)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([i,u])=>{let a=t?t+i:i;if(typeof u=="object")Nr(u,a+".",r,o);else if(typeof u=="string"||typeof u=="number")o(a,u.toString());else if(typeof u=="boolean")o(a,u?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof u}`)})},Ue=e=>{let t=Le(),r=t.stackSave();try{let o=t.stackAlloc(8);t._OrtGetLastError(o,o+4);let i=t.HEAP32[o/4],u=t.HEAPU32[o/4+1],a=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(r)}};var Ni=e=>{let t=Le(),r=0,o=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let u=0;return e?.tag!==void 0&&(u=Fe(e.tag,o)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,u),r===0&&Ue("Can\'t create run options."),e?.extra!==void 0&&Nr(e.extra,"",new WeakSet,(a,c)=>{let p=Fe(a,o),h=Fe(c,o);t._OrtAddRunConfigEntry(r,p,h)!==0&&Ue(`Can\'t set a run config entry: ${a} - ${c}.`)}),[r,o]}catch(u){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(a=>t._free(a)),u}};var gl=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},yl=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},bl=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},wl=(e,t,r)=>{for(let o of t){let i=typeof o=="string"?o:o.name;switch(i){case"webnn":if(i="WEBNN",typeof o!="string"){let a=o;if(a?.deviceType){let c=Fe("deviceType",r),p=Fe(a.deviceType,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'deviceType\' - ${a.deviceType}.`)}if(a?.numThreads){let c=a.numThreads;(typeof c!="number"||!Number.isInteger(c)||c<0)&&(c=0);let p=Fe("numThreads",r),h=Fe(c.toString(),r);Le()._OrtAddSessionConfigEntry(e,p,h)!==0&&Ue(`Can\'t set a session config entry: \'numThreads\' - ${a.numThreads}.`)}if(a?.powerPreference){let c=Fe("powerPreference",r),p=Fe(a.powerPreference,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'powerPreference\' - ${a.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof o!="string"){let a=o;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${a.preferredLayout}`);let c=Fe("preferredLayout",r),p=Fe(a.preferredLayout,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'preferredLayout\' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let u=Fe(i,r);Le()._OrtAppendExecutionProvider(e,u)!==0&&Ue(`Can\'t append execution provider: ${i}.`)}},Gi=e=>{let t=Le(),r=0,o=[],i=e||{};bl(i);try{let u=gl(i.graphOptimizationLevel??"all"),a=yl(i.executionMode??"sequential"),c=typeof i.logId=="string"?Fe(i.logId,o):0,p=i.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=i.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let d=typeof i.optimizedModelFilePath=="string"?Fe(i.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(u,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,c,p,h,d),r===0&&Ue("Can\'t create session options."),i.executionProviders&&wl(r,i.executionProviders,o),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let y=Fe("enableGraphCapture",o),w=Fe(i.enableGraphCapture.toString(),o);t._OrtAddSessionConfigEntry(r,y,w)!==0&&Ue(`Can\'t set a session config entry: \'enableGraphCapture\' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[y,w]of Object.entries(i.freeDimensionOverrides)){if(typeof y!="string")throw new Error(`free dimension override name must be a string: ${y}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let _=Fe(y,o);t._OrtAddFreeDimensionOverride(r,_,w)!==0&&Ue(`Can\'t set a free dimension override: ${y} - ${w}.`)}return i.extra!==void 0&&Nr(i.extra,"",new WeakSet,(y,w)=>{let _=Fe(y,o),v=Fe(w,o);t._OrtAddSessionConfigEntry(r,_,v)!==0&&Ue(`Can\'t set a session config entry: ${y} - ${w}.`)}),[r,o]}catch(u){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(a=>t._free(a)),u}};ye();var Li=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(e),o=[];for await(let i of r)o.push(i);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),o=r?parseInt(r,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),u;try{u=new ArrayBuffer(o)}catch(c){if(c instanceof RangeError){let p=Math.ceil(o/65536);u=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw c}let a=0;for(;;){let{done:c,value:p}=await i.read();if(c)break;let h=p.byteLength;new Uint8Array(u,a,h).set(p),a+=h}return new Uint8Array(u,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var im=(e,t)=>{Le()._OrtInit(e,t)!==0&&Ue("Can\'t initialize onnxruntime.")},Ld=async e=>{im(e.wasm.numThreads,Gr(e.logLevel))},Fd=async(e,t)=>{{let r=(Gd(),wr(Nd)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let o=e.webgpu.adapter;if(o){if(typeof o.limits!="object"||typeof o.features!="object"||typeof o.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(o=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:u}),!o)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\')}if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",Le(),e,o)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Le(),e)}}},ar=new Map,am=e=>{let t=Le(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&Ue("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},Xo=e=>{let t=Le(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},qd=async(e,t)=>{let r,o,i=Le();Array.isArray(e)?[r,o]=e:e.buffer===i.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=Xo(e);let u=0,a=0,c=0,p=[],h=[],d=[];try{if([a,p]=Gi(t),t?.externalData&&i.mountExternalData){let x=[];for(let E of t.externalData){let P=typeof E=="string"?E:E.path;x.push(Li(typeof E=="string"?E:E.data).then(O=>{i.mountExternalData(P,O)}))}await Promise.all(x)}u=await i._OrtCreateSession(r,o,a),u===0&&Ue("Can\'t create a session.");let[y,w]=am(u),_=!!t?.enableGraphCapture,v=[],S=[],A=[];for(let x=0;xx==="gpu-buffer")&&(c=i._OrtCreateBinding(u),c===0&&Ue("Can\'t create IO binding."),I={handle:c,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(x=>yo(x))}),ar.set(u,[u,h,d,I,_,!1]),[u,v,S]}catch(y){throw h.forEach(w=>i._OrtFree(w)),d.forEach(w=>i._OrtFree(w)),c!==0&&i._OrtReleaseBinding(c),u!==0&&i._OrtReleaseSession(u),y}finally{i._free(r),a!==0&&i._OrtReleaseSessionOptions(a),p.forEach(y=>i._free(y)),i.unmountExternalData?.()}},jd=e=>{let t=Le(),r=ar.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,i,u,a,c]=r;a&&(c&&t._OrtClearBoundOutputs(a.handle),t._OrtReleaseBinding(a.handle)),t.jsepOnReleaseSession?.(e),i.forEach(p=>t._OrtFree(p)),u.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(o),ar.delete(e)},Hd=(e,t,r,o,i,u=!1)=>{if(!e){t.push(0);return}let a=Le(),c=e[0],p=e[1],h=e[3],d,y;if(c==="string"&&h==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(u&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let v=e[2].gpuBuffer,S=tr(go(c));y=p.reduce((I,x)=>I*x,1)*S;let A=a.jsepRegisterBuffer;if(!A)throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');d=A(o,i,v,y)}else{let v=e[2];if(Array.isArray(v)){y=4*v.length,d=a._malloc(y),r.push(d);let S=d/4;for(let A=0;Aa.HEAP32[v++]=A);let S=a._OrtCreateTensor(go(c),d,y,_,p.length,yo(h));S===0&&Ue(`Can\'t create tensor for input/output. session=${o}, index=${i}.`),t.push(S)}finally{a.stackRestore(w)}},Kd=async(e,t,r,o,i,u)=>{let a=Le(),c=ar.get(e);if(!c)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=c[0],h=c[1],d=c[2],y=c[3],w=c[4],_=c[5],v=t.length,S=o.length,A=0,I=[],x=[],E=[],P=[],O=a.stackSave(),R=a.stackAlloc(v*4),L=a.stackAlloc(v*4),N=a.stackAlloc(S*4),K=a.stackAlloc(S*4);try{[A,I]=Ni(u);for(let ee=0;eeNe*Ye,1);ue=Gt(ne);let Ut=y?.outputPreferredLocations[o[ee]];if(ue==="string"){if(Ut==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ne=[],Ye=le/4;for(let mt=0;mt0){let Ne=a.jsepGetBuffer;if(!Ne)throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');let Ye=Ne(le),mt=tr(ne);if(mt===void 0||!Hi(ue))throw new Error(`Unsupported data type: ${ue}`);ie=!0,We.push([ue,Be,{gpuBuffer:Ye,download:a.jsepCreateDownloader(Ye,Ge*mt,ue),dispose:()=>{a._OrtReleaseTensor(ae)}},"gpu-buffer"])}else{let Ne=bn(ue),Ye=new Ne(Ge);new Uint8Array(Ye.buffer,Ye.byteOffset,Ye.byteLength).set(a.HEAPU8.subarray(le,le+Ye.byteLength)),We.push([ue,Be,Ye,"cpu"])}}finally{a.stackRestore(Ae),ue==="string"&&le&&a._free(le),ie||a._OrtReleaseTensor(ae)}}return y&&!w&&(a._OrtClearBoundOutputs(y.handle),ar.set(e,[p,h,d,y,w,!1])),We}finally{a.stackRestore(O),x.forEach(Q=>a._OrtReleaseTensor(Q)),E.forEach(Q=>a._OrtReleaseTensor(Q)),P.forEach(Q=>a._free(Q)),A!==0&&a._OrtReleaseRunOptions(A),I.forEach(Q=>a._free(Q))}},Yd=e=>{let t=Le(),r=ar.get(e);if(!r)throw new Error("invalid session id");let o=r[0],i=t._OrtEndProfiling(o);i===0&&Ue("Can\'t get an profile file name."),t._OrtFree(i)},Zd=e=>{let t=[];for(let r of e){let o=r[2];!Array.isArray(o)&&"buffer"in o&&t.push(o.buffer)}return t};self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Wi(r.wasm).then(()=>{Ld(r).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:i}=r;Fd(i,o).then(()=>{postMessage({type:t})},u=>{postMessage({type:t,err:u})});break}case"copy-from":{let{buffer:o}=r,i=Xo(o);postMessage({type:t,out:i});break}case"create":{let{model:o,options:i}=r;qd(o,i).then(u=>{postMessage({type:t,out:u})},u=>{postMessage({type:t,err:u})});break}case"release":jd(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:i,inputs:u,outputIndices:a,options:c}=r;Kd(o,i,u,a,new Array(a.length).fill(null),c).then(p=>{p.some(h=>h[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:p},Zd([...u,...p]))},p=>{postMessage({type:t,err:p})});break}case"end-profiling":Yd(r),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}};})();\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n'}),Si,dr,Ra,$s,Rs,ec,qo,Vi,Hi,Wm,Is,iw,aw,sw,ow,lw,uw,cw,dw=Ce(()=>{Ur(),V2(),ao(),Si=()=>!!Kt.wasm.proxy&&typeof document<"u",Ra=!1,$s=!1,Rs=!1,qo=new Map,Vi=(n,e)=>{let t=qo.get(n);t?t.push(e):qo.set(n,[e])},Hi=()=>{if(Ra||!$s||Rs||!dr)throw new Error("worker not ready")},Wm=n=>{switch(n.data.type){case"init-wasm":Ra=!1,n.data.err?(Rs=!0,ec[1](n.data.err)):($s=!0,ec[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=qo.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},Is=typeof document<"u"?document?.currentScript?.src:void 0,iw=async()=>{if(!$s){if(Ra)throw new Error("multiple calls to 'initWasm()' detected.");if(Rs)throw new Error("previous call to 'initWasm()' failed.");if(Ra=!0,Si())return Kt.wasm.wasmPaths===void 0&&Is&&Is.indexOf("blob:")!==0&&(Kt.wasm.wasmPaths=Is.substr(0,+Is.lastIndexOf("/")+1)),new Promise((n,e)=>{dr?.terminate();let t=URL.createObjectURL(new Blob([H2()],{type:"text/javascript"}));dr=new Worker(t,{name:"ort-wasm-proxy-worker"}),dr.onerror=i=>e(i),dr.onmessage=Wm,URL.revokeObjectURL(t),ec=[n,e];let r={type:"init-wasm",in:Kt};dr.postMessage(r)});try{await _0(Kt.wasm),await Zv(Kt),$s=!0}catch(n){throw Rs=!0,n}finally{Ra=!1}}},aw=async n=>{if(Si())return Hi(),new Promise((e,t)=>{Vi("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Kt}};dr.postMessage(r)});await Qv(Kt,n)},sw=async n=>Si()?(Hi(),new Promise((e,t)=>{Vi("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};dr.postMessage(r,[n.buffer])})):Zc(n),ow=async(n,e)=>{if(Si()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Hi(),new Promise((t,r)=>{Vi("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},a=[];n instanceof Uint8Array&&a.push(n.buffer),dr.postMessage(i,a)})}else return Jv(n,e)},lw=async n=>{if(Si())return Hi(),new Promise((e,t)=>{Vi("release",[e,t]);let r={type:"release",in:n};dr.postMessage(r)});ew(n)},uw=async(n,e,t,r,i,a)=>{if(Si()){if(t.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return Hi(),new Promise((s,o)=>{Vi("run",[s,o]);let l=t,u={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:a}};dr.postMessage(u,rw(l))})}else return tw(n,e,t,r,i,a)},cw=async n=>{if(Si())return Hi(),new Promise((e,t)=>{Vi("end-profiling",[e,t]);let r={type:"end-profiling",in:n};dr.postMessage(r)});nw(n)}}),tc,Vm,hw,q2=Ce(()=>{Ur(),dw(),bt(),w0(),tc=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},Vm=n=>{switch(n[3]){case"cpu":return new jn(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!xd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return jn.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},hw=class{async fetchModelAndCopyToWasmMemory(n){return sw(await Ol(n))}async loadModel(n,e){Nr();let t;typeof n=="string"?typeof process<"u"&&process.versions&&process.versions.node?t=await Ol(n):t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames]=await ow(t,e),yr()}async dispose(){return lw(this.sessionId)}async run(n,e,t){Nr();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],d=h[1],m=this.inputNames.indexOf(p);if(m===-1)throw new Error(`invalid input '${p}'`);r.push(d),i.push(m)});let a=[],s=[];Object.entries(e).forEach(h=>{let p=h[0],d=h[1],m=this.outputNames.indexOf(p);if(m===-1)throw new Error(`invalid output '${p}'`);a.push(d),s.push(m)});let o=r.map((h,p)=>tc(h,()=>`input "${this.inputNames[i[p]]}"`)),l=a.map((h,p)=>h?tc(h,()=>`output "${this.outputNames[s[p]]}"`):null),u=await uw(this.sessionId,i,o,s,l,t),c={};for(let h=0;h{Ur(),dw(),q2(),Hm=()=>{if((typeof Kt.wasm.initTimeout!="number"||Kt.wasm.initTimeout<0)&&(Kt.wasm.initTimeout=0),typeof Kt.wasm.simd!="boolean"&&(Kt.wasm.simd=!0),typeof Kt.wasm.proxy!="boolean"&&(Kt.wasm.proxy=!1),typeof Kt.wasm.trace!="boolean"&&(Kt.wasm.trace=!1),typeof Kt.wasm.numThreads!="number"||!Number.isInteger(Kt.wasm.numThreads)||Kt.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Kt.wasm.numThreads=1);let n=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Kt.wasm.numThreads=Math.min(4,Math.ceil((n||1)/2))}},pw=class{async init(n){Hm(),await iw(),await aw(n)}async createInferenceSessionHandler(n,e){let t=new hw;return await t.loadModel(n,e),Promise.resolve(t)}}}),fw={};ms(fw,{wasmBackend:()=>mw});var mw,X2=Ce(()=>{j2(),mw=new pw});Ur();Ur();Ur();var Y2="1.18.0",K2=l0;{let n=(X2(),la(fw)).wasmBackend;aa("webgpu",n,5),aa("webnn",n,5),aa("cpu",n,10),aa("wasm",n,10)}Object.defineProperty(Kt.versions,"web",{value:Y2,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */const Z2=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return gd},get TRACE(){return js},get TRACE_FUNC_BEGIN(){return Nr},get TRACE_FUNC_END(){return yr},get Tensor(){return jn},get TrainingSession(){return _d},default:K2,get env(){return Kt},get registerBackend(){return aa}},Symbol.toStringTag,{value:"Module"})),Q2=(n,e)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=n.dims[3],t.height=n.dims[2];const r=t.getContext("2d");if(r!=null){let i,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],a=n.dims[3]):(i=n.dims[3],a=n.dims[2]);const s=e?.format!==void 0?e.format:"RGB",o=e?.norm;let l,u;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?u=[0,0,0,0]:typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:(u=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(u[3]=o.bias[3]));const c=a*i;let h=0,p=c,d=c*2,m=-1;s==="RGBA"?(h=0,p=c,d=c*2,m=c*3):s==="RGB"?(h=0,p=c,d=c*2):s==="RBG"&&(h=0,d=c,p=c*2);for(let y=0;y{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(t!=null){let i,a,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],a=n.dims[1],s=n.dims[3]):(i=n.dims[3],a=n.dims[2],s=n.dims[1]);const o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm;let u,c;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?c=[0,0,0,0]:typeof l.bias=="number"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[3]=l.bias[3]));const h=a*i;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const p=4;let d=0,m=1,y=2,g=3,_=0,w=h,b=h*2,E=-1;o==="RGBA"?(_=0,w=h,b=h*2,E=h*3):o==="RGB"?(_=0,w=h,b=h*2):o==="RBG"&&(_=0,b=h,w=h*2),r=t.createImageData(i,a);for(let T=0;T{if(n===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:r}=e,i=e.norm??{mean:255,bias:0};let a,s;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=t*r,c=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let h=4,p=0,d=1,m=2,y=3,g=0,_=u,w=u*2,b=-1;o==="RGB"&&(h=3,p=0,d=1,m=2,y=-1),l==="RGBA"?b=u*3:l==="RBG"?(g=0,w=u,_=u*2):l==="BGR"&&(w=0,_=u,g=u*2);for(let T=0;T{const t=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,r=typeof ImageData<"u"&&n instanceof ImageData,i=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,a=typeof n=="string";let s,o=e??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(t){const c=l();c.width=n.width,c.height=n.height;const h=u(c);if(h!=null){let p=n.height,d=n.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(p=e.resizedHeight,d=e.resizedWidth),e!==void 0){if(o=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=p,o.width=d}else o.tensorFormat="RGBA",o.height=p,o.width=d;h.drawImage(n,0,0),s=h.getImageData(0,0,d,p).data}else throw new Error("Can not access image data")}else if(r){let c,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,h=e.resizedWidth):(c=n.height,h=n.width),e!==void 0&&(o=e),o.format="RGBA",o.height=c,o.width=h,e!==void 0){const p=l();p.width=h,p.height=c;const d=u(p);if(d!=null)d.putImageData(n,0,0),s=d.getImageData(0,0,h,c).data;else throw new Error("Can not access image data")}else s=n.data}else if(i){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");const c=l();c.width=n.width,c.height=n.height;const h=u(c);if(h!=null){const p=n.height,d=n.width;return h.drawImage(n,0,0,d,p),s=h.getImageData(0,0,d,p).data,o.height=p,o.width=d,nc(s,o)}else throw new Error("Can not access image data")}else{if(a)return new Promise((c,h)=>{const p=l(),d=u(p);if(!n||!d)return h();const m=new Image;m.crossOrigin="Anonymous",m.src=n,m.onload=()=>{p.width=m.width,p.height=m.height,d.drawImage(m,0,0,p.width,p.height);const y=d.getImageData(0,0,p.width,p.height);o.height=p.height,o.width=p.width,c(nc(y.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return nc(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},tS=(n,e)=>{const{width:t,height:r,download:i,dispose:a}=e,s=[1,r,t,4];return new jr({location:"texture",type:"float32",texture:n,dims:s,download:i,dispose:a})},nS=(n,e)=>{const{dataType:t,dims:r,download:i,dispose:a}=e;return new jr({location:"gpu-buffer",type:t??"float32",gpuBuffer:n,dims:r,download:i,dispose:a})},rS=(n,e,t)=>new jr({location:"cpu-pinned",type:n,data:e,dims:t??[e.length]}),ts=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Ml=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let qm=!1;const iS=()=>{if(!qm){qm=!0;const n=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,t=typeof Float16Array<"u"&&Float16Array.from;n&&(ts.set("int64",BigInt64Array),Ml.set(BigInt64Array,"int64")),e&&(ts.set("uint64",BigUint64Array),Ml.set(BigUint64Array,"uint64")),t?(ts.set("float16",Float16Array),Ml.set(Float16Array,"float16")):ts.set("float16",Uint16Array)}},aS=n=>{let e=1;for(let t=0;t{switch(n.location){case"cpu":return new jr(n.type,n.data,e);case"cpu-pinned":return new jr({location:"cpu-pinned",data:n.data,type:n.type,dims:e});case"texture":return new jr({location:"texture",texture:n.texture,type:n.type,dims:e});case"gpu-buffer":return new jr({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}};let jr=class{constructor(e,t,r){iS();let i,a;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,a=e.dims,e.location){case"cpu-pinned":{const o=ts.get(i);if(!o)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,l;if(typeof e=="string")if(i=e,l=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{const u=ts.get(e);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&u===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?o=u.from(t,BigInt):o=u.from(t)}else if(t instanceof u)o=t;else throw new TypeError(`A ${i} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof e[0];if(u==="string")i="string",o=e;else if(u==="boolean")i="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else{const u=Ml.get(e.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=u,o=e}if(l===void 0)l=[o.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=o,this.dataLocation="cpu"}const s=aS(a);if(this.cpuData&&s!==this.cpuData.length)throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=a,this.size=s}static async fromImage(e,t){return eS(e,t)}static fromTexture(e,t){return tS(e,t)}static fromGpuBuffer(e,t){return nS(e,t)}static fromPinnedBuffer(e,t,r){return rS(e,t,r)}toDataURL(e){return Q2(this,e)}toImageData(e){return J2(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return sS(this,e)}};const oS=jr,Bs=[];let Qc,Ks;pa.IS_NODE_ENV?(Ks=un??c1,Bs.push("cpu"),Qc=["cpu"]):(Ks=Z2,pa.IS_WEBGPU_AVAILABLE&&Bs.push("webgpu"),Bs.push("wasm"),Qc=["wasm"]);const lS=Ks.InferenceSession;function uS(n){let e=Qc;if(n){if(!Bs.includes(n))throw new Error(`Unsupported device: "${n}". Should be one of: ${Bs.join(", ")}.`);e=[n]}return e}async function gw(n,e){return await lS.create(n,e)}function _w(n){return n instanceof Ks.Tensor}const na=Ks?.env;na?.wasm&&(na.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/",na.wasm.proxy=!pa.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(na.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(na.wasm.simd=!1));function cS(){return na?.wasm?.proxy}er.backends.onnx=na;const Ia=async(n,e,t)=>{const r=await gw(new Uint8Array(n),e);return async i=>{const a=Object.fromEntries(Object.entries(i).map(([o,l])=>[o,l.ort_tensor])),s=await r.run(a);return Array.isArray(t)?t.map(o=>new je(s[o])):new je(s[t])}};class Fl{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Ia([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Ia([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Ia([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Ia([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Ia([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Ia([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}const jm=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class je{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return _w(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new oS(e[0],e[1],e[2]),new Proxy(this,{get:(t,r)=>{if(typeof r=="string"){let i=Number(r);if(Number.isInteger(i))return t._getitem(i)}return t[r]},set:(t,r,i)=>t[r]=i})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const r=t.reduce((i,a)=>i*a);for(let i=0;i0){const i=r.reduce((a,s)=>a*s);return this._subarray(e,i,r)}else return new je(this.type,[this.data[e]],r)}indexOf(e){const t=this.data;for(let r=0;rp)throw new Error(`Invalid slice: ${c}`);let d=[Math.max(h,0),Math.min(p,this.dims[u])];r.push(d),t.push(d[1]-d[0])}else throw new Error(`Invalid slice: ${c}`)}let i=r.map(([u,c])=>c-u),a=i.reduce((u,c)=>u*c);const s=this.data;let o=new s.constructor(a);const l=this.stride();for(let u=0;u=0;--h){const d=i[h];c+=(p%d+r[h][0])*l[h],p=Math.floor(p/d)}o[u]=s[c]}return new je(this.type,o,t)}permute(...e){return hS(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,r=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);const i=this.data;if(t===null){let o=i.reduce((l,u)=>l+u**e,0)**(1/e);return new je(this.type,[o],[])}t=Vr(t,this.dims.length);const a=this.dims.slice();a[t]=1;const s=new i.constructor(i.length/this.dims[t]);for(let o=0;o=0;--u){const p=this.dims[u];if(u!==t){const d=c%p;l+=d*h,h*=a[u]}c=Math.floor(c/p)}s[l]+=i[o]**e}if(e!==1)for(let o=0;o=0;--o){const c=this.dims[o];if(o!==t){const h=l%c;s+=h*u,u*=this.dims[o]}l=Math.floor(l/c)}i[a]/=r.data[s]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return _S(this.dims)}squeeze(e=null){return new je(this.type,this.data,Ym(this.dims,e))}squeeze_(e=null){return this.dims=Ym(this.dims,e),this}unsqueeze(e=null){return new je(this.type,this.data,Km(this.dims,e))}unsqueeze_(e=null){return this.dims=Km(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let r=this.dims.slice(0,e),i=this.dims.slice(e,t+1),a=this.dims.slice(t+1);return this.dims=[...r,i.reduce((s,o)=>s*o,1),...a],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let r=0;rs!==t?i*a:i,1);e[t]=this.data.length/r}return new je(this.type,this.data,e)}neg_(){const e=this.data;for(let t=0;ta*s);if(t!==r)throw Error(`cannot reshape array of size ${t} into shape (${e})`);let i=n;for(let a=e.length-1;a>=0;a--)i=i.reduce((s,o)=>{let l=s[s.length-1];return l.lengtht!==1):typeof e=="number"?n[e]===1&&n.splice(e,1):Array.isArray(e)&&(n=n.filter((t,r)=>t!==1||!e.includes(r))),n}function Km(n,e){return e=Vr(e,n.length+1),n=n.slice(),n.splice(e,0,1),n}function Vr(n,e,t=null,r=!0){if(r&&(n<-e||n>=e))throw new Error(`IndexError: index ${n} is out of bounds for dimension${t===null?"":" "+t} with size ${e}`);return n<0&&(n=(n%e+e)%e),n}function Xr(n,e=0){e=Vr(e,n[0].dims.length);const t=n[0].dims.slice();t[e]=n.reduce((s,o)=>s+o.dims[e],0);const r=t.reduce((s,o)=>s*o,1),i=new n[0].data.constructor(r),a=n[0].type;if(e===0){let s=0;for(let o of n)i.set(o.data,s),s+=o.data.length}else{let s=0;for(let o=0;o=0;--h){const m=l.dims[h];let y=p%m;h===e&&(y+=s),c+=y*d,d*=t[h],p=Math.floor(p/m)}i[c]=l.data[u]}s+=l.dims[e]}}return new je(a,i,t)}function Zs(n,e=0){return Xr(n.map(t=>t.unsqueeze(e)),e)}function mS(n,e=null,t=1,r=!1){if(e===null){const u=n.data.reduce((d,m)=>d+m,0)/n.data.length,c=Math.sqrt(n.data.reduce((d,m)=>d+(m-u)**2,0)/(n.data.length-t)),h=new je(n.type,[u],[]);return[new je(n.type,[c],[]),h]}e=Vr(e,n.dims.length);const i=Dd(n,e,r),a=n.dims.slice();a[e]=1;const s=new n.data.constructor(n.data.length/n.dims[e]);for(let l=0;l=0;--c){const d=n.dims[c];if(c!==e){const m=h%d;u+=m*p,p*=a[c]}h=Math.floor(h/d)}s[u]+=(n.data[l]-i.data[u])**2}for(let l=0;ls+o,0);return new je(n.type,[a/n.data.length],[])}e=Vr(e,n.dims.length);const r=n.dims.slice();r[e]=1;const i=new n.data.constructor(n.data.length/n.dims[e]);for(let a=0;a=0;--o){const c=n.dims[o];if(o!==e){const h=l%c;s+=h*u,u*=r[o]}l=Math.floor(l/c)}i[s]+=n.data[a]}if(n.dims[e]!==1)for(let a=0;a0||o>0;)switch(l.push(s-1),u.push(o-1),a[s][o].item()){case 0:--s,--o;break;case 1:--s;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${o}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}function _S(n){const e=new Array(n.length);for(let t=n.length-1,r=1;t>=0;--t)e[t]=r,r*=n[t];return e}function Ld(n,e,t,r){const i=n.reduce((a,s)=>a*s,1);return new je(t,new r(i).fill(e),n)}function yS(n,e){let t,r;if(typeof e=="number")t="float32",r=Float32Array;else if(typeof e=="bigint")t="int64",r=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof e}`);return Ld(n,e,t,r)}function vS(n,e){return yS(n.dims,e)}function oo(n){return Ld(n,1n,"int64",BigInt64Array)}function wS(n){return oo(n.dims)}function bS(n){return Ld(n,0n,"int64",BigInt64Array)}function xS(n){return bS(n.dims)}function SS(n,e){if(n.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(n.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");const t=e==="binary",r=t?"int8":"uint8",i=t?Int8Array:Uint8Array,a=n.data,s=new i(a.length/8);for(let o=0;o0?1:0,u=Math.floor(o/8),c=o%8;s[u]|=l<<7-c,t&&c===0&&(s[u]-=128)}return new je(r,s,[n.dims[0],n.dims[1]/8])}class ES{constructor(e=(r,i)=>r>i,t=1/0){this._heap=[],this._comparator=e,this._maxSize=t}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size0&&this._swap(0,t),this._heap.pop(),this._siftDown(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._siftDown(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const i=new Fs(this.bosTokenId,0,0,0,0),a=new Fs(this.eosTokenId,1,this.len,0,0);this.nodes.push(i.clone()),this.nodes.push(a.clone()),this.beginNodes[this.len].push(a),this.endNodes[0].push(i)}insert(e,t,r,i){const a=this.nodes.length,s=new Fs(i,a,e,t,r);this.beginNodes[e].push(s),this.endNodes[e+t].push(s),this.nodes.push(s)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(this.beginNodes[t].length==0)return[];for(let o of this.beginNodes[t]){o.prev=null;let l=0,u=null;for(let c of this.endNodes[t]){const h=c.backtraceScore+o.score;(u===null||h>l)&&(u=c.clone(),l=h)}if(u!==null)o.prev=u,o.backtraceScore=l;else return[]}++t}const r=[],a=this.beginNodes[e][0].prev;if(a===null)return[];let s=a.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){return this.viterbi().map(t=>this.piece(t))}tokenIds(){return this.viterbi().map(t=>t.tokenId)}}class Fs{constructor(e,t,r,i,a){this.tokenId=e,this.nodeId=t,this.pos=r,this.length=i,this.score=a,this.prev=null,this.backtraceScore=0}clone(){const e=new Fs(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}var pe=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),Zm=Object.freeze({set:pe.Set,for:pe.For,in:pe.In,is:pe.Is,if:pe.If,else:pe.Else,endif:pe.EndIf,elif:pe.ElseIf,endfor:pe.EndFor,and:pe.And,or:pe.Or,not:pe.Not,"not in":pe.NotIn,true:pe.BooleanLiteral,false:pe.BooleanLiteral}),qi=class{constructor(n,e){this.value=n,this.type=e}};function Qm(n){return/\w/.test(n)}function rc(n){return/[0-9]/.test(n)}var AS=[["{%",pe.OpenStatement],["%}",pe.CloseStatement],["{{",pe.OpenExpression],["}}",pe.CloseExpression],["(",pe.OpenParen],[")",pe.CloseParen],["{",pe.OpenCurlyBracket],["}",pe.CloseCurlyBracket],["[",pe.OpenSquareBracket],["]",pe.CloseSquareBracket],[",",pe.Comma],[".",pe.Dot],[":",pe.Colon],["|",pe.Pipe],["<=",pe.ComparisonBinaryOperator],[">=",pe.ComparisonBinaryOperator],["==",pe.ComparisonBinaryOperator],["!=",pe.ComparisonBinaryOperator],["<",pe.ComparisonBinaryOperator],[">",pe.ComparisonBinaryOperator],["+",pe.AdditiveBinaryOperator],["-",pe.AdditiveBinaryOperator],["*",pe.MultiplicativeBinaryOperator],["/",pe.MultiplicativeBinaryOperator],["%",pe.MultiplicativeBinaryOperator],["=",pe.Equals]],CS=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function $S(n,e={}){return n.endsWith(` `)&&(n=n.slice(0,-1)),n=n.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(n=n.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(n=n.replace(/([#%]})\n/g,"$1")),n.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function RS(n,e={}){const t=[],r=$S(n,e);let i=0;const a=s=>{let o="";for(;s(r[i]);){if(r[i]==="\\"){if(++i,i>=r.length)throw new SyntaxError("Unexpected end of input");const l=r[i++],u=CS.get(l);if(u===void 0)throw new SyntaxError(`Unexpected escaped character: ${l}`);o+=u;continue}if(o+=r[i++],i>=r.length)throw new SyntaxError("Unexpected end of input")}return o};e:for(;i0){t.push(new qi(l,pe.Text));continue}}a(l=>/\s/.test(l));const o=r[i];if(o==="-"||o==="+"){const l=t.at(-1)?.type;if(l===pe.Text||l===void 0)throw new SyntaxError(`Unexpected character: ${o}`);switch(l){case pe.Identifier:case pe.NumericLiteral:case pe.BooleanLiteral:case pe.StringLiteral:case pe.CloseParen:case pe.CloseSquareBracket:break;default:{++i;const u=a(rc);t.push(new qi(`${o}${u}`,u.length>0?pe.NumericLiteral:pe.UnaryOperator));continue}}}for(const[l,u]of AS)if(r.slice(i,i+l.length)===l){t.push(new qi(l,u)),i+=l.length;continue e}if(o==="'"||o==='"'){++i;const l=a(u=>u!==o);t.push(new qi(l,pe.StringLiteral)),++i;continue}if(rc(o)){const l=a(rc);t.push(new qi(l,pe.NumericLiteral));continue}if(Qm(o)){const l=a(Qm),u=Object.hasOwn(Zm,l)?Zm[l]:pe.Identifier;u===pe.In&&t.at(-1)?.type===pe.Not?(t.pop(),t.push(new qi("not in",pe.NotIn))):t.push(new qi(l,u));continue}throw new SyntaxError(`Unexpected character: ${o}`)}return t}var lo=class{type="Statement"},IS=class extends lo{constructor(n){super(),this.body=n}type="Program"},Jm=class extends lo{constructor(n,e,t){super(),this.test=n,this.body=e,this.alternate=t}type="If"},PS=class extends lo{constructor(n,e,t){super(),this.loopvar=n,this.iterable=e,this.body=t}type="For"},kS=class extends lo{constructor(n,e){super(),this.assignee=n,this.value=e}type="Set"},Kr=class extends lo{type="Expression"},OS=class extends Kr{constructor(n,e,t){super(),this.object=n,this.property=e,this.computed=t}type="MemberExpression"},DS=class extends Kr{constructor(n,e){super(),this.callee=n,this.args=e}type="CallExpression"},Pa=class extends Kr{constructor(n){super(),this.value=n}type="Identifier"},_s=class extends Kr{constructor(n){super(),this.value=n}type="Literal"},LS=class extends _s{type="NumericLiteral"},eg=class extends _s{type="StringLiteral"},tg=class extends _s{type="BooleanLiteral"},zS=class extends _s{type="ArrayLiteral"},ng=class extends _s{type="TupleLiteral"},NS=class extends _s{type="ObjectLiteral"},Ps=class extends Kr{constructor(n,e,t){super(),this.operator=n,this.left=e,this.right=t}type="BinaryExpression"},US=class extends Kr{constructor(n,e){super(),this.operand=n,this.filter=e}type="FilterExpression"},BS=class extends Kr{constructor(n,e,t){super(),this.operand=n,this.negate=e,this.test=t}type="TestExpression"},FS=class extends Kr{constructor(n,e){super(),this.operator=n,this.argument=e}type="UnaryExpression"},GS=class extends Kr{constructor(n=void 0,e=void 0,t=void 0){super(),this.start=n,this.stop=e,this.step=t}type="SliceExpression"},WS=class extends Kr{constructor(n,e){super(),this.key=n,this.value=e}type="KeywordArgumentExpression"};function VS(n){const e=new IS([]);let t=0;function r($,L){const H=n[t++];if(!H||H.type!==$)throw new Error(`Parser Error: ${L}. ${H.type} !== ${$}.`);return H}function i(){switch(n[t].type){case pe.Text:return o();case pe.OpenStatement:return l();case pe.OpenExpression:return u();default:throw new SyntaxError(`Unexpected token type: ${n[t].type}`)}}function a(...$){return t+$.length<=n.length&&$.some((L,H)=>L!==n[t+H].type)}function s(...$){return t+$.length<=n.length&&$.every((L,H)=>L===n[t+H].type)}function o(){return new eg(r(pe.Text,"Expected text token").value)}function l(){r(pe.OpenStatement,"Expected opening statement token");let $;switch(n[t].type){case pe.Set:++t,$=c(),r(pe.CloseStatement,"Expected closing statement token");break;case pe.If:++t,$=h(),r(pe.OpenStatement,"Expected {% token"),r(pe.EndIf,"Expected endif token"),r(pe.CloseStatement,"Expected %} token");break;case pe.For:++t,$=d(),r(pe.OpenStatement,"Expected {% token"),r(pe.EndFor,"Expected endfor token"),r(pe.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${n[t].type}`)}return $}function u(){r(pe.OpenExpression,"Expected opening expression token");const $=m();return r(pe.CloseExpression,"Expected closing expression token"),$}function c(){const $=m();if(s(pe.Equals)){++t;const L=c();return new kS($,L)}return $}function h(){const $=m();r(pe.CloseStatement,"Expected closing statement token");const L=[],H=[];for(;!(n[t]?.type===pe.OpenStatement&&(n[t+1]?.type===pe.ElseIf||n[t+1]?.type===pe.Else||n[t+1]?.type===pe.EndIf));)L.push(i());if(n[t]?.type===pe.OpenStatement&&n[t+1]?.type!==pe.EndIf)if(++t,s(pe.ElseIf))r(pe.ElseIf,"Expected elseif token"),H.push(h());else for(r(pe.Else,"Expected else token"),r(pe.CloseStatement,"Expected closing statement token");!(n[t]?.type===pe.OpenStatement&&n[t+1]?.type===pe.EndIf);)H.push(i());return new Jm($,L,H)}function p($=!1){const L=$?F:m,H=[L()],K=s(pe.Comma);for(;K&&(++t,H.push(L()),!!s(pe.Comma)););return K?new ng(H):H[0]}function d(){const $=p(!0);if(!($ instanceof Pa||$ instanceof ng))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${$.type} instead`);r(pe.In,"Expected `in` keyword following loop variable");const L=m();r(pe.CloseStatement,"Expected closing statement token");const H=[];for(;a(pe.OpenStatement,pe.EndFor);)H.push(i());return new PS($,L,H)}function m(){return y()}function y(){const $=g();if(s(pe.If)){++t;const L=g();r(pe.Else,"Expected else token");const H=g();return new Jm(L,[$],[H])}return $}function g(){let $=_();for(;s(pe.Or);){const L=n[t];++t;const H=_();$=new Ps(L,$,H)}return $}function _(){let $=w();for(;s(pe.And);){const L=n[t];++t;const H=w();$=new Ps(L,$,H)}return $}function w(){let $;for(;s(pe.Not);){const L=n[t];++t;const H=w();$=new FS(L,H)}return $??b()}function b(){let $=E();for(;s(pe.ComparisonBinaryOperator)||s(pe.In)||s(pe.NotIn);){const L=n[t];++t;const H=E();$=new Ps(L,$,H)}return $}function E(){let $=j();for(;s(pe.AdditiveBinaryOperator);){const L=n[t];++t;const H=j();$=new Ps(L,$,H)}return $}function T(){const $=k();return s(pe.OpenParen)?I($):$}function I($){let L=new DS($,C());return s(pe.OpenParen)&&(L=I(L)),L}function C(){r(pe.OpenParen,"Expected opening parenthesis for arguments list");const $=B();return r(pe.CloseParen,"Expected closing parenthesis for arguments list"),$}function B(){const $=[];for(;!s(pe.CloseParen);){let L=m();if(s(pe.Equals)){if(++t,!(L instanceof Pa))throw new SyntaxError("Expected identifier for keyword argument");const H=m();L=new WS(L,H)}$.push(L),s(pe.Comma)&&++t}return $}function R(){const $=[];let L=!1;for(;!s(pe.CloseSquareBracket);)s(pe.Colon)?($.push(void 0),++t,L=!0):($.push(m()),s(pe.Colon)&&(++t,L=!0));if($.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if($.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new GS(...$)}return $[0]}function k(){let $=F();for(;s(pe.Dot)||s(pe.OpenSquareBracket);){const L=n[t];++t;let H;const K=L.type!==pe.Dot;if(K)H=R(),r(pe.CloseSquareBracket,"Expected closing square bracket");else if(H=F(),H.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");$=new OS($,H,K)}return $}function j(){let $=Q();for(;s(pe.MultiplicativeBinaryOperator);){const L=n[t];++t;const H=Q();$=new Ps(L,$,H)}return $}function Q(){let $=ie();for(;s(pe.Is);){++t;const L=s(pe.Not);L&&++t;let H=F();if(H instanceof tg&&(H=new Pa(H.value.toString())),!(H instanceof Pa))throw new SyntaxError("Expected identifier for the test");$=new BS($,L,H)}return $}function ie(){let $=T();for(;s(pe.Pipe);){++t;let L=F();if(!(L instanceof Pa))throw new SyntaxError("Expected identifier for the filter");s(pe.OpenParen)&&(L=I(L)),$=new US($,L)}return $}function F(){const $=n[t];switch($.type){case pe.NumericLiteral:return++t,new LS(Number($.value));case pe.StringLiteral:return++t,new eg($.value);case pe.BooleanLiteral:return++t,new tg($.value==="true");case pe.Identifier:return++t,new Pa($.value);case pe.OpenParen:{++t;const L=p();if(n[t].type!==pe.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${n[t].type} instead`);return++t,L}case pe.OpenSquareBracket:{++t;const L=[];for(;!s(pe.CloseSquareBracket);)L.push(m()),s(pe.Comma)&&++t;return++t,new zS(L)}case pe.OpenCurlyBracket:{++t;const L=new Map;for(;!s(pe.CloseCurlyBracket);){const H=m();r(pe.Colon,"Expected colon between key and value in object literal");const K=m();L.set(H,K),s(pe.Comma)&&++t}return++t,new NS(L)}default:throw new SyntaxError(`Unexpected token: ${$.type}`)}}for(;t=0?(e=(e??=0)<0?Math.max(n.length+e,0):Math.min(e,n.length),t=(t??=n.length)<0?Math.max(n.length+t,0):Math.min(t,n.length)):(e=(e??=n.length-1)<0?Math.max(n.length+e,-1):Math.min(e,n.length-1),t=(t??=-1)<-1?Math.max(n.length+t,-1):Math.min(t,n.length-1));const a=[];for(let s=e;i*se.toUpperCase())}var mi=class{type="RuntimeValue";value;builtins=new Map;constructor(n=void 0){this.value=n}__bool__(){return new pn(!!this.value)}},nn=class extends mi{type="NumericValue"},Ft=class extends mi{type="StringValue";builtins=new Map([["upper",new ci(()=>new Ft(this.value.toUpperCase()))],["lower",new ci(()=>new Ft(this.value.toLowerCase()))],["strip",new ci(()=>new Ft(this.value.trim()))],["title",new ci(()=>new Ft(yw(this.value)))],["length",new nn(this.value.length)]])},pn=class extends mi{type="BooleanValue"},kr=class extends mi{type="ObjectValue";__bool__(){return new pn(this.value.size>0)}builtins=new Map([["get",new ci(([n,e])=>{if(!(n instanceof Ft))throw new Error(`Object key must be a string: got ${n.type}`);return this.value.get(n.value)??e??new Gs})],["items",new ci(()=>new ln(Array.from(this.value.entries()).map(([n,e])=>new ln([new Ft(n),e]))))]])},ln=class extends mi{type="ArrayValue";builtins=new Map([["length",new nn(this.value.length)]]);__bool__(){return new pn(this.value.length>0)}},qS=class extends ln{type="TupleValue"},ci=class extends mi{type="FunctionValue"},Gs=class extends mi{type="NullValue"},Pr=class extends mi{type="UndefinedValue"},Jc=class{constructor(n){this.parent=n}variables=new Map([["namespace",new ci(n=>{if(n.length===0)return new kr(new Map);if(n.length!==1||!(n[0]instanceof kr))throw new Error("`namespace` expects either zero arguments or a single object argument");return n[0]})]]);tests=new Map([["boolean",n=>n.type==="BooleanValue"],["callable",n=>n instanceof ci],["odd",n=>{if(n.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${n.type}`);return n.value%2!==0}],["even",n=>{if(n.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${n.type}`);return n.value%2===0}],["false",n=>n.type==="BooleanValue"&&!n.value],["true",n=>n.type==="BooleanValue"&&n.value],["number",n=>n.type==="NumericValue"],["integer",n=>n.type==="NumericValue"&&Number.isInteger(n.value)],["iterable",n=>n instanceof ln||n instanceof Ft],["lower",n=>{const e=n.value;return n.type==="StringValue"&&e===e.toLowerCase()}],["upper",n=>{const e=n.value;return n.type==="StringValue"&&e===e.toUpperCase()}],["none",n=>n.type==="NullValue"],["defined",n=>n.type!=="UndefinedValue"],["undefined",n=>n.type==="UndefinedValue"],["equalto",(n,e)=>n.value===e.value]]);set(n,e){return this.declareVariable(n,Tl(e))}declareVariable(n,e){if(this.variables.has(n))throw new SyntaxError(`Variable already declared: ${n}`);return this.variables.set(n,e),e}setVariable(n,e){return this.variables.set(n,e),e}resolve(n){if(this.variables.has(n))return this;if(this.parent)return this.parent.resolve(n);throw new Error(`Unknown variable: ${n}`)}lookupVariable(n){try{return this.resolve(n).variables.get(n)??new Pr}catch{return new Pr}}},jS=class{global;constructor(n){this.global=n??new Jc}run(n){return this.evaluate(n,this.global)}evaluateBinaryExpression(n,e){const t=this.evaluate(n.left,e);switch(n.operator.value){case"and":return t.__bool__().value?this.evaluate(n.right,e):t;case"or":return t.__bool__().value?t:this.evaluate(n.right,e)}const r=this.evaluate(n.right,e);switch(n.operator.value){case"==":return new pn(t.value==r.value);case"!=":return new pn(t.value!=r.value)}if(t instanceof Pr||r instanceof Pr)throw new Error("Cannot perform operation on undefined values");if(t instanceof Gs||r instanceof Gs)throw new Error("Cannot perform operation on null values");if(t instanceof nn&&r instanceof nn)switch(n.operator.value){case"+":return new nn(t.value+r.value);case"-":return new nn(t.value-r.value);case"*":return new nn(t.value*r.value);case"/":return new nn(t.value/r.value);case"%":return new nn(t.value%r.value);case"<":return new pn(t.value":return new pn(t.value>r.value);case">=":return new pn(t.value>=r.value);case"<=":return new pn(t.value<=r.value)}else if(t instanceof ln&&r instanceof ln)switch(n.operator.value){case"+":return new ln(t.value.concat(r.value))}else if(r instanceof ln){const i=r.value.find(a=>a.value===t.value)!==void 0;switch(n.operator.value){case"in":return new pn(i);case"not in":return new pn(!i)}}if(t instanceof Ft||r instanceof Ft)switch(n.operator.value){case"+":return new Ft(t.value.toString()+r.value.toString())}if(t instanceof Ft&&r instanceof Ft)switch(n.operator.value){case"in":return new pn(r.value.includes(t.value));case"not in":return new pn(!r.value.includes(t.value))}if(t instanceof Ft&&r instanceof kr)switch(n.operator.value){case"in":return new pn(r.value.has(t.value));case"not in":return new pn(!r.value.has(t.value))}throw new SyntaxError(`Unknown operator "${n.operator.value}" between ${t.type} and ${r.type}`)}evaluateFilterExpression(n,e){const t=this.evaluate(n.operand,e);if(n.filter.type==="Identifier"){const r=n.filter;if(t instanceof ln)switch(r.value){case"list":return t;case"first":return t.value[0];case"last":return t.value[t.value.length-1];case"length":return new nn(t.value.length);case"reverse":return new ln(t.value.reverse());case"sort":return new ln(t.value.sort((i,a)=>{if(i.type!==a.type)throw new Error(`Cannot compare different types: ${i.type} and ${a.type}`);switch(i.type){case"NumericValue":return i.value-a.value;case"StringValue":return i.value.localeCompare(a.value);default:throw new Error(`Cannot compare type: ${i.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(t instanceof Ft)switch(r.value){case"length":return new nn(t.value.length);case"upper":return new Ft(t.value.toUpperCase());case"lower":return new Ft(t.value.toLowerCase());case"title":return new Ft(yw(t.value));case"capitalize":return new Ft(t.value.charAt(0).toUpperCase()+t.value.slice(1));case"trim":return new Ft(t.value.trim());default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else if(t instanceof nn)switch(r.value){case"abs":return new nn(Math.abs(t.value));default:throw new Error(`Unknown NumericValue filter: ${r.value}`)}else if(t instanceof kr)switch(r.value){case"items":return new ln(Array.from(t.value.entries()).map(([i,a])=>new ln([new Ft(i),a])));case"length":return new nn(t.value.size);default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}throw new Error(`Cannot apply filter "${r.value}" to type: ${t.type}`)}else if(n.filter.type==="CallExpression"){const r=n.filter;if(r.callee.type!=="Identifier")throw new Error(`Unknown filter: ${r.callee.type}`);const i=r.callee.value;if(t instanceof ln){switch(i){case"selectattr":{if(t.value.some(c=>!(c instanceof kr)))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some(c=>c.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[a,s,o]=r.args.map(c=>this.evaluate(c,e));let l;if(s){const c=e.tests.get(s.value);if(!c)throw new Error(`Unknown test: ${s.value}`);l=c}else l=(...c)=>c[0].__bool__().value;const u=t.value.filter(c=>{const h=c.value.get(a.value);return h?l(h,o):!1});return new ln(u)}}throw new Error(`Unknown ArrayValue filter: ${i}`)}else throw new Error(`Cannot apply filter "${i}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${n.filter.type}`)}evaluateTestExpression(n,e){const t=this.evaluate(n.operand,e),r=e.tests.get(n.test.value);if(!r)throw new Error(`Unknown test: ${n.test.value}`);const i=r(t);return new pn(n.negate?!i:i)}evaluateUnaryExpression(n,e){const t=this.evaluate(n.argument,e);switch(n.operator.value){case"not":return new pn(!t.value);default:throw new SyntaxError(`Unknown operator: ${n.operator.value}`)}}evalProgram(n,e){return this.evaluateBlock(n.body,e)}evaluateBlock(n,e){let t="";for(const r of n){const i=this.evaluate(r,e);i.type!=="NullValue"&&i.type!=="UndefinedValue"&&(t+=i.value)}return new Ft(t)}evaluateIdentifier(n,e){return e.lookupVariable(n.value)}evaluateCallExpression(n,e){const t=[],r=new Map;for(const a of n.args)if(a.type==="KeywordArgumentExpression"){const s=a;r.set(s.key.value,this.evaluate(s.value,e))}else t.push(this.evaluate(a,e));r.size>0&&t.push(new kr(r));const i=this.evaluate(n.callee,e);if(i.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(t,e)}evaluateSliceExpression(n,e,t){if(!(n instanceof ln||n instanceof Ft))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,t),i=this.evaluate(e.stop,t),a=this.evaluate(e.step,t);if(!(r instanceof nn||r instanceof Pr))throw new Error("Slice start must be numeric or undefined");if(!(i instanceof nn||i instanceof Pr))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof nn||a instanceof Pr))throw new Error("Slice step must be numeric or undefined");return n instanceof ln?new ln(rg(n.value,r.value,i.value,a.value)):new Ft(rg(Array.from(n.value),r.value,i.value,a.value).join(""))}evaluateMemberExpression(n,e){const t=this.evaluate(n.object,e);let r;if(n.computed){if(n.property.type==="SliceExpression")return this.evaluateSliceExpression(t,n.property,e);r=this.evaluate(n.property,e)}else r=new Ft(n.property.value);let i;if(t instanceof kr){if(!(r instanceof Ft))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=t.value.get(r.value)??t.builtins.get(r.value)}else if(t instanceof ln||t instanceof Ft)if(r instanceof nn)i=t.value.at(r.value),t instanceof Ft&&(i=new Ft(t.value.at(r.value)));else if(r instanceof Ft)i=t.builtins.get(r.value);else throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof Ft))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=t.builtins.get(r.value)}return i instanceof mi?i:new Pr}evaluateSet(n,e){const t=this.evaluate(n.value,e);if(n.assignee.type==="Identifier"){const r=n.assignee.value;e.setVariable(r,t)}else if(n.assignee.type==="MemberExpression"){const r=n.assignee,i=this.evaluate(r.object,e);if(!(i instanceof kr))throw new Error("Cannot assign to member of non-object");if(r.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");i.value.set(r.property.value,t)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(n.assignee)}`);return new Gs}evaluateIf(n,e){const t=this.evaluate(n.test,e);return this.evaluateBlock(t.__bool__().value?n.body:n.alternate,e)}evaluateFor(n,e){const t=new Jc(e),r=this.evaluate(n.iterable,t);if(!(r instanceof ln))throw new Error(`Expected iterable type in for loop: got ${r.type}`);let i="";for(let a=0;a0?r.value[a-1]:new Pr],["nextitem",ac.value.length?"few":"many"} items to unpack`);for(let h=0;hthis.evaluate(t,e)));case"TupleLiteral":return new qS(n.value.map(t=>this.evaluate(t,e)));case"ObjectLiteral":{const t=new Map;for(const[r,i]of n.value){const a=this.evaluate(r,e);if(!(a instanceof Ft))throw new Error(`Object keys must be strings: got ${a.type}`);t.set(a.value,this.evaluate(i,e))}return new kr(t)}case"Identifier":return this.evaluateIdentifier(n,e);case"CallExpression":return this.evaluateCallExpression(n,e);case"MemberExpression":return this.evaluateMemberExpression(n,e);case"UnaryExpression":return this.evaluateUnaryExpression(n,e);case"BinaryExpression":return this.evaluateBinaryExpression(n,e);case"FilterExpression":return this.evaluateFilterExpression(n,e);case"TestExpression":return this.evaluateTestExpression(n,e);default:throw new SyntaxError(`Unknown node type: ${n.type}`)}}};function Tl(n){switch(typeof n){case"number":return new nn(n);case"string":return new Ft(n);case"boolean":return new pn(n);case"object":return n===null?new Gs:Array.isArray(n)?new ln(n.map(Tl)):new kr(new Map(Object.entries(n).map(([e,t])=>[e,Tl(t)])));case"function":return new ci((e,t)=>{const r=n(...e.map(i=>i.value))??null;return Tl(r)});default:throw new Error(`Cannot convert to runtime value: ${n}`)}}var XS=class{parsed;constructor(n){const e=RS(n,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=VS(e)}render(n){const e=new Jc;e.set("false",!1),e.set("true",!0),e.set("raise_exception",i=>{throw new Error(i)}),e.set("range",HS);for(const[i,a]of Object.entries(n))e.set(i,a);return new jS(e).run(this.parsed).value}};const vw=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],Al=new Map(vw),YS=new Map([...vw.map(([n,e])=>[e,n]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function ww(n){n=n.toLowerCase();let e=YS.get(n);if(e===void 0)if(Al.has(n))e=n;else{const r=n.length===2?Al.keys():Al.values();throw new Error(`Language "${n}" is not supported. Must be one of: ${JSON.stringify(r)}`)}return e}const ic="https://github.com/xenova/transformers.js/issues/new/choose";async function bw(n,e){const t=await Promise.all([Ii(n,"tokenizer.json",!0,e),Ii(n,"tokenizer_config.json",!0,e)]);return e.legacy!==null&&(t[1].legacy=e.legacy),t}function KS(n,e){const t=[];let r=0;for(const i of n.matchAll(e)){const a=i[0];r0&&t.push(a),r=i.index+a.length}return r=19968&&n<=40959||n>=13312&&n<=19903||n>=131072&&n<=173791||n>=173824&&n<=177983||n>=177984&&n<=178207||n>=178208&&n<=183983||n>=63744&&n<=64255||n>=194560&&n<=195103}function JS(n,e,t){const r=[];let i=0;for(;ithis.tokens_to_ids.get(t)??this.unk_token_id)}convert_ids_to_tokens(e){return e.map(t=>this.vocab[t]??this.unk_token)}}class rE extends uo{constructor(e){super(e),this.tokens_to_ids=zd(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){const t=[];for(const r of e){const i=[...r];if(i.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let a=!1,s=0;const o=[];for(;s0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){u=c;break}--l}if(u===null){a=!0;break}o.push(u),s=l}a?t.push(this.unk_token):t.push(...o)}return t}}class iE extends uo{constructor(e,t){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let i=0;i[i,a])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=t.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=W_(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new MS,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.sentence,r=t.length;let i=0;for(;i{const n=[...Array.from({length:94},(i,a)=>a+33),...Array.from({length:12},(i,a)=>a+161),...Array.from({length:82},(i,a)=>a+174)],e=n.slice();let t=0;for(let i=0;i<256;++i)n.includes(i)||(n.push(i),e.push(256+t),t+=1);const r=e.map(i=>String.fromCharCode(i));return Object.fromEntries(n.map((i,a)=>[i,r[a]]))})(),aE=_1(Ew);class sE extends uo{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=zd(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[t,r]of this.tokens_to_ids)this.vocab[r]=t;this.bpe_ranks=new Map(e.merges.map((t,r)=>[t,r])),this.merges=e.merges.map(t=>t.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(e){if(e.length===0)return[];const t=this.cache.get(e);if(t!==void 0)return t;const r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let i=[];if(r.length>1){const a=new ES((l,u)=>l.score`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`)):t.push(this.unk_token)}return t}}class oE extends uo{constructor(e,t){super(e),this.tokens_to_ids=zd(t.target_lang?e.vocab[t.target_lang]:e.vocab),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[r,i]of this.tokens_to_ids)this.vocab[i]=r}encode(e){return e}}class lr extends Nn{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new _E(e);case"Precompiled":return new LE(e);case"Sequence":return new gE(e);case"Replace":return new lE(e);case"NFC":return new uE(e);case"NFKC":return new cE(e);case"NFKD":return new dE(e);case"Strip":return new hE(e);case"StripAccents":return new pE(e);case"Lowercase":return new fE(e);case"Prepend":return new mE(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class lE extends lr{normalize(e){const t=tu(this.config.pattern);return t===null?e:e.replaceAll(t,this.config.content)}}class uE extends lr{normalize(e){return e=e.normalize("NFC"),e}}class cE extends lr{normalize(e){return e=e.normalize("NFKC"),e}}class dE extends lr{normalize(e){return e=e.normalize("NFKD"),e}}class hE extends lr{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class pE extends lr{normalize(e){return e=Sw(e),e}}class fE extends lr{normalize(e){return e=e.toLowerCase(),e}}class mE extends lr{normalize(e){return e=this.config.prepend+e,e}}class gE extends lr{constructor(e){super(e),this.normalizers=e.normalizers.map(t=>lr.fromConfig(t))}normalize(e){return this.normalizers.reduce((t,r)=>r.normalize(t),e)}}class _E extends lr{_tokenize_chinese_chars(e){const t=[];for(let r=0;rthis.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}}class yE extends vr{constructor(e){super(),this.pattern=new RegExp(`[^\\s${Qs}]+|[${Qs}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class vE extends vr{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=Ew,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(i=>Array.from(this.text_encoder.encode(i),a=>this.byte_encoder[a]).join(""))}}class wE extends vr{constructor(e){super(),this.config=e,this.pattern=tu(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:KS(e,this.pattern)}}class bE extends vr{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Qs}]+|[${Qs}]+`,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class xE extends vr{constructor(e){super(),this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class us extends Nn{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new SE(e);case"ByteLevel":return new Aw(e);case"RobertaProcessing":return new Tw(e);case"BertProcessing":return new Mw(e);case"Sequence":return new EE(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...t){throw Error("post_process should be implemented in subclass.")}_call(e,...t){return this.post_process(e,...t)}}class Mw extends us{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,t=null,{add_special_tokens:r=!0}={}){r&&(e=Cn([this.cls],e,[this.sep]));let i=new Array(e.length).fill(0);if(t!==null){const a=r&&this instanceof Tw?[this.sep]:[],s=r?[this.sep]:[];e=Cn(e,a,t,s),i=Cn(i,new Array(t.length+a.length+s.length).fill(1))}return{tokens:e,token_type_ids:i}}}class Tw extends Mw{}class SE extends us{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,t=null,{add_special_tokens:r=!0}={}){const i=t===null?this.single:this.pair;let a=[],s=[];for(const o of i)"SpecialToken"in o?r&&(a.push(o.SpecialToken.id),s.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(a=Cn(a,e),s=Cn(s,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(a=Cn(a,t),s=Cn(s,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:a,token_type_ids:s}}}class Aw extends us{post_process(e,t=null){return t&&(e=Cn(e,t)),{tokens:e}}}class EE extends us{constructor(e){super(e),this.processors=e.processors.map(t=>us.fromConfig(t))}post_process(e,t=null,r={}){let i;for(const a of this.processors)if(a instanceof Aw)e=a.post_process(e).tokens,t&&(t=a.post_process(t).tokens);else{const s=a.post_process(e,t,r);e=s.tokens,i=s.token_type_ids}return{tokens:e,token_type_ids:i}}}class ur extends Nn{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(e===null)return null;switch(e.type){case"WordPiece":return new $E(e);case"Metaspace":return new DE(e);case"ByteLevel":return new RE(e);case"Replace":return new ME(e);case"ByteFallback":return new TE(e);case"Fuse":return new AE(e);case"Strip":return new CE(e);case"Sequence":return new PE(e);case"CTC":return new IE(e);case"BPEDecoder":return new kE(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class ME extends ur{decode_chain(e){const t=tu(this.config.pattern);return t===null?e:e.map(r=>r.replaceAll(t,this.config.content))}}class TE extends ur{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let r=[];for(const i of e){let a=null;if(i.length===6&&i.startsWith("<0x")&&i.endsWith(">")){const s=parseInt(i.slice(3,5),16);isNaN(s)||(a=s)}if(a!==null)r.push(a);else{if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));t.push(s),r=[]}t.push(i)}}if(r.length>0){const i=this.text_decoder.decode(Uint8Array.from(r));t.push(i),r=[]}return t}}class AE extends ur{decode_chain(e){return[e.join("")]}}class CE extends ur{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map(t=>{let r=0;for(let a=0;a(r!==0&&(t.startsWith(this.config.prefix)?t=t.replace(this.config.prefix,""):t=" "+t),this.cleanup&&(t=Nd(t)),t))}}class RE extends ur{constructor(e){super(e),this.byte_decoder=aE,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),r=new Uint8Array([...t].map(a=>this.byte_decoder[a]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const i of e)this.added_tokens.find(a=>a.content===i)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(i)):r.push(i);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}}class IE extends ur{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const t=[e[0]];for(let a=1;aa!==this.pad_token).join("");return this.cleanup&&(i=Nd(i).replaceAll(this.word_delimiter_token," ").trim()),i}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class PE extends ur{constructor(e){super(e),this.decoders=e.decoders.map(t=>ur.fromConfig(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}}class kE extends ur{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}}class OE extends ur{decode_chain(e){let t="";for(let r=1;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}}class zE extends vr{constructor(e){super(),this.tokenizers=e.pretokenizers.map(t=>vr.fromConfig(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,i)=>i.pre_tokenize(r,t),[e])}}class NE extends vr{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class UE extends vr{constructor(e){super()}pre_tokenize_text(e,t){return eE(e)}}class BE extends vr{constructor(e){super(),this.config=e,this.pattern=tu(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,t){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const FE=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function GE(n,e,t,r){for(const i of Object.keys(n)){const a=e-n[i].length,s=t(i),o=new Array(a).fill(s);n[i]=r==="right"?Cn(n[i],o):Cn(o,n[i])}}function WE(n,e){for(const t of Object.keys(n))n[t].length=e}class At extends Nn{return_token_type_ids=!1;_default_chat_template=`{% for message in messages %}{{'<|im_start|>' + message['role'] + ' ' + message['content'] + '<|im_end|>' + ' '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant ' }}{% endif %}`;padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=lr.fromConfig(e.normalizer),this.pre_tokenizer=vr.fromConfig(e.pre_tokenizer),this.model=uo.fromConfig(e.model,t),this.post_processor=us.fromConfig(e.post_processor),this.decoder=ur.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const r of e.added_tokens){const i=new nE(r);this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id))}if(this.additional_special_tokens=t.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.map(r=>`${r.lstrip?"\\s*":""}(${G_(r.content)})${r.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,t.padding_side&&(this.padding_side=t.padding_side),this.legacy=!1,this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const r=Object.create(null);for(const{name:i,template:a}of this.chat_template){if(typeof i!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');r[i]=a}this.chat_template=r}this._compiled_template_cache=new Map}getToken(...e){for(const t of e){const r=this._tokenizer_config[t];if(r)if(typeof r=="object"){if(r.__type==="AddedToken")return r.content;throw Error(`Unknown token: ${r}`)}else return r}return null}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",legacy:o=null}={}){const l=await bw(e,{progress_callback:t,config:r,cache_dir:i,local_files_only:a,revision:s,legacy:o});return new this(...l)}_call(e,{text_pair:t=null,add_special_tokens:r=!0,padding:i=!1,truncation:a=null,max_length:s=null,return_tensor:o=!0,return_token_type_ids:l=null}={}){const u=Array.isArray(e);let c;if(u){if(e.length===0)throw Error("text array must be non-empty");if(t!==null){if(Array.isArray(t)){if(e.length!==t.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");c=e.map((p,d)=>this._encode_plus(p,{text_pair:t[d],add_special_tokens:r,return_token_type_ids:l}))}else c=e.map(p=>this._encode_plus(p,{add_special_tokens:r,return_token_type_ids:l}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");c=[this._encode_plus(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:l})]}if(s===null?i==="max_length"?s=this.model_max_length:s=wr(c.map(p=>p.input_ids.length))[0]:a||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),s=Math.min(s,this.model_max_length??1/0),i||a)for(let p=0;ps?a&&WE(c[p],s):i&&GE(c[p],s,d=>d==="input_ids"?this.pad_token_id:0,this.padding_side));const h={};if(o){if(!(i&&a)&&c.some(d=>{for(const m of Object.keys(d))if(d[m].length!==c[0][m]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const p=[c.length,c[0].input_ids.length];for(const d of Object.keys(c[0]))h[d]=new je("int64",BigInt64Array.from(c.flatMap(m=>m[d]).map(BigInt)),p)}else{for(const p of Object.keys(c[0]))h[p]=c.map(d=>d[p]);if(!u)for(const p of Object.keys(h))h[p]=h[p][0]}return h}_encode_text(e){return e===null?null:(this.added_tokens_regex?e.split(this.added_tokens_regex).filter(i=>i):[e]).map((i,a)=>{if(this.added_tokens.find(o=>o.content===i)!==void 0)return i;{if(this.remove_space===!0&&(i=i.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(i=ZS(i)),this.normalizer!==null&&(i=this.normalizer(i)),i.length===0)return[];const o=this.pre_tokenizer!==null?this.pre_tokenizer(i,{section_index:a}):[i];return this.model(o)}}).flat()}_encode_plus(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:i=null}={}){const{tokens:a,token_type_ids:s}=this._tokenize_helper(e,{pair:t,add_special_tokens:r}),o=this.model.convert_tokens_to_ids(a),l={input_ids:o,attention_mask:new Array(o.length).fill(1)};return(i??this.return_token_type_ids)&&s&&(l.token_type_ids=s),l}_tokenize_helper(e,{pair:t=null,add_special_tokens:r=!1}={}){const i=this._encode_text(e),a=this._encode_text(t);return this.post_processor?this.post_processor(i,a,{add_special_tokens:r}):{tokens:Cn(i??[],a??[])}}tokenize(e,{pair:t=null,add_special_tokens:r=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:r}).tokens}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:i=null}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:i}).input_ids}batch_decode(e,t={}){return e instanceof je&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof je&&(e=xw(e)),!Array.isArray(e)||e.length===0||!y1(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:r=null}){let i=this.model.convert_ids_to_tokens(e);t&&(i=i.filter(s=>!this.special_tokens.includes(s)));let a=this.decoder?this.decoder(i):i.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(a=a.replaceAll(this.decoder.end_of_word_suffix," "),t&&(a=a.trim())),(r??this.clean_up_tokenization_spaces)&&(a=Nd(a)),a}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(e,{chat_template:t=null,add_generation_prompt:r=!1,tokenize:i=!0,padding:a=!1,truncation:s=!1,max_length:o=null,return_tensor:l=!0,return_dict:u=!1,tokenizer_kwargs:c={},...h}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null&&this.default_chat_template&&typeof this.default_chat_template=="object"){const y=this.chat_template??this.default_chat_template;if(t!==null&&Object.hasOwn(y,t))t=y[t];else if(t===null&&"default"in y)t=y.default;else if(t===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(y).sort()}.`)}else t??=this.chat_template??this.default_chat_template;if(typeof t!="string")throw Error(`chat_template must be a string, but got ${typeof t}`);let p=this._compiled_template_cache.get(t);p===void 0&&(p=new XS(t),this._compiled_template_cache.set(t,p));const d=Object.create(null);for(const y of FE){const g=this.getToken(y);g&&(d[y]=g)}const m=p.render({messages:e,add_generation_prompt:r,...d,...h});if(i){const y=this._call(m,{add_special_tokens:!1,padding:a,truncation:s,max_length:o,return_tensor:l,...c});return u?y:y.input_ids}return m}}class VE extends At{return_token_type_ids=!0}class HE extends At{return_token_type_ids=!0}class qE extends At{return_token_type_ids=!0}class jE extends At{return_token_type_ids=!0}class XE extends At{return_token_type_ids=!0}class YE extends At{return_token_type_ids=!0}class KE extends At{return_token_type_ids=!0}class ZE extends At{return_token_type_ids=!0}class QE extends At{return_token_type_ids=!0}class JE extends At{}class eM extends At{}class tM extends At{return_token_type_ids=!0;constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class nM extends At{return_token_type_ids=!0}class rM extends At{}class $w extends At{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}'}class iM extends At{}class Rw extends At{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Ud(this,e,t,r)}}class aM extends Rw{}class sM extends At{}class oM extends $w{constructor(e,t){const r=".,!?…。,、।۔،",i=e.pre_tokenizer?.pretokenizers[0]?.pattern;i&&i.Regex===` ?[^(\\s|[${r}])]+`&&(i.Regex=` ?[^\\s${r}]+`),super(e,t)}}const jo="▁";class Iw extends At{_default_chat_template=`{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> ' + system_message + ' <> ' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> ' + content.strip() + ' <> ' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`;DEFAULT_SYSTEM_PROMPT=`You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.`;padding_side="left";constructor(e,t){super(e,t),this.use_default_system_prompt=t.use_default_system_prompt??!1,this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Cw({replacement:jo,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(e){if(e===null)return null;if(this.legacy||e.length===0)return super._encode_text(e);let t=super._encode_text(jo+e.replaceAll(jo," "));return t.length>1&&t[0]===jo&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll(` `,"\\n").replaceAll("'","\\'"))}}class lM extends Iw{}class uM extends At{}class cM extends At{}class dM extends At{}class hM extends At{}class pM extends At{}class fM extends At{}class mM extends At{_default_chat_template=`{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + ' ' + message['content'] | trim + ' ' }}{% endfor %}{% if add_generation_prompt %}{{'model '}}{% endif %}`}class gM extends At{}function Ud(n,e,t,r){if(!("language_codes"in n)||!Array.isArray(n.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in n)||!(n.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in n)||typeof n.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const i=r.src_lang,a=r.tgt_lang;if(!n.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${n.language_codes.join(", ")}}`);if(i!==void 0){if(!n.language_codes.includes(i))throw new Error(`Source language code "${i}" is not valid. Must be one of: {${n.language_codes.join(", ")}}`);for(const s of n.post_processor.config.single)if("SpecialToken"in s&&n.languageRegex.test(s.SpecialToken.id)){s.SpecialToken.id=n.lang_to_token(i);break}}return r.forced_bos_token_id=n.model.convert_tokens_to_ids([n.lang_to_token(a)])[0],n._call(e,t)}class _M extends At{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Ud(this,e,t,r)}}class yM extends At{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return Ud(this,e,t,r)}}class vM extends At{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}';get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:i=null,force_full_sequences:a=!0}={}){if(i===null)throw Error("Must specify time_precision");let s=null;const o=t==="word";function l(){return{language:s,timestamp:[null,null],text:""}}const u=[];let c=l(),h=0;const p=this.timestamp_begin;let d=[],m=[],y=!1,g=null;const _=new Set(this.all_special_ids);for(const E of e){const T=E.tokens,I=o?E.token_timestamps:null;let C=null,B=p;if("stride"in E){const[j,Q,ie]=E.stride;if(h-=Q,g=j-ie,Q&&(B=Q/i+p),ie)for(let F=T.length-1;F>=0;--F){const $=Number(T[F]);if($>=p){if(C!==null&&($-p)*i=p){const ie=(Q-p)*i+h,F=wl(ie,2);if(C!==null&&Q>=C)y=!0;else if(y||d.length>0&&Q0?(d.push(R),o&&m.push(k)):d.every(j=>j.length===0)&&(c=l(),d=[],R=[],m=[],k=[])}if(d.length>0){if(a&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[E,T]=this.findLongestCommonSequence(d,m),I=this.decode(E);c.text=I,o&&(c.words=this.collateWordTimestamps(E,T,s)),u.push(c)}let w=Object.create(null);const b=u.map(E=>E.text).join("");if(t||r){for(let E=0;E0;let o=s?[]:null,l=s?t[0]:null;for(let u=1;uF===j[$]).length,ie=Q/E+T;Q>1&&ie>h&&(h=ie,p=[I,C,R,k])}const[m,y,g,_]=p,w=Math.floor((y+m)/2),b=Math.floor((_+g)/2);a.push(...r.slice(0,w)),r=c.slice(b),i=r.length,s&&(o.push(...l.slice(0,w)),l=t[u].slice(b))}return a.push(...r),s?(o.push(...l),[a,o]):[a,[]]}collateWordTimestamps(e,t,r){const[i,a,s]=this.combineTokensIntoWords(e,r),o=[];for(let l=0;l=i){const o=((s-i)*r).toFixed(2);a.push(`<|${o}|>`),a.push([])}else a[a.length-1].push(s);return a=a.map(s=>typeof s=="string"?s:super.decode(s,t)),a.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",i=[],a=[],s=[];let o=[],l=[],u=0;for(let c=0;c=this.model.tokens_to_ids.get("<|endoftext|>"),m=c.startsWith(" "),y=c.trim(),g=l.test(y);if(d||m||g||a.length===0)a.push(c),s.push(h),o.push(p);else{const _=a.length-1;a[_]+=c,s[_].push(...h),o[_].push(...p)}}return[a,s,o]}mergePunctuations(e,t,r,i,a){const s=structuredClone(e),o=structuredClone(t),l=structuredClone(r);let u=s.length-2,c=s.length-1;for(;u>=0;)s[u].startsWith(" ")&&i.includes(s[u].trim())?(s[c]=s[u]+s[c],o[c]=Cn(o[u],o[c]),l[c]=Cn(l[u],l[c]),s[u]="",o[u]=[],l[u]=[]):c=u,--u;for(u=0,c=1;ch),o.filter(h=>h.length>0),l.filter(h=>h.length>0)]}get_decoder_prompt_ids({language:e=null,task:t=null,no_timestamps:r=!0}={}){const i=[];if(e){const a=ww(e),s=this.model.tokens_to_ids.get(`<|${a}|>`);if(s===void 0)throw new Error(`Unable to find language "${a}" in model vocabulary. Please report this issue at ${ic}.`);i.push(s)}else i.push(null);if(t){if(t=t.toLowerCase(),t!=="transcribe"&&t!=="translate")throw new Error(`Task "${t}" is not supported. Must be one of: ["transcribe", "translate"]`);const a=this.model.tokens_to_ids.get(`<|${t}|>`);if(a===void 0)throw new Error(`Unable to find task "${t}" in model vocabulary. Please report this issue at ${ic}.`);i.push(a)}else i.push(null);if(r){const a=this.model.tokens_to_ids.get("<|notimestamps|>");if(a===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${ic}.`);i.push(a)}return i.map((a,s)=>[s+1,a]).filter(a=>a[1]!==null)}}class wM extends At{}class bM extends At{}class xM extends At{}class SM extends At{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(r=>this.languageRegex.test(r)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){const[i,a]=r;return this.supported_language_codes.includes(i)||console.warn(`Unsupported language code "${i}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Cn([i],super._encode_text(a))}}}class EM extends At{}class Pw extends At{_default_chat_template="{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}"}class MM extends Pw{}class TM extends At{}class AM extends At{}class CM extends At{constructor(e,t){super(e,t),this.decoder=new OE({})}}class $M extends At{}class Tn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:rM,DistilBertTokenizer:JE,CamembertTokenizer:eM,DebertaTokenizer:XE,DebertaV2Tokenizer:YE,BertTokenizer:VE,HerbertTokenizer:KE,ConvBertTokenizer:ZE,RoFormerTokenizer:QE,XLMTokenizer:tM,ElectraTokenizer:nM,MobileBertTokenizer:qE,SqueezeBertTokenizer:jE,AlbertTokenizer:HE,GPT2Tokenizer:$w,BartTokenizer:iM,MBartTokenizer:Rw,MBart50Tokenizer:aM,RobertaTokenizer:sM,WhisperTokenizer:vM,CodeGenTokenizer:wM,CLIPTokenizer:bM,SiglipTokenizer:xM,MarianTokenizer:SM,BloomTokenizer:oM,NllbTokenizer:_M,M2M100Tokenizer:yM,LlamaTokenizer:Iw,CodeLlamaTokenizer:lM,XLMRobertaTokenizer:uM,MPNetTokenizer:cM,FalconTokenizer:dM,GPTNeoXTokenizer:hM,EsmTokenizer:pM,Wav2Vec2CTCTokenizer:EM,BlenderbotTokenizer:Pw,BlenderbotSmallTokenizer:MM,SpeechT5Tokenizer:TM,NougatTokenizer:AM,VitsTokenizer:CM,Qwen2Tokenizer:fM,GemmaTokenizer:mM,Grok1Tokenizer:gM,CohereTokenizer:$M,PreTrainedTokenizer:At};static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",legacy:o=null}={}){const[l,u]=await bw(e,{progress_callback:t,config:r,cache_dir:i,local_files_only:a,revision:s,legacy:o}),c=u.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let h=this.TOKENIZER_CLASS_MAPPING[c];return h||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),h=At),new h(l,u)}}async function RM(n,e){return await Ii(n,"config.json",!0,e)}function Qa(n){const e={};let t={};switch(n.model_type){case"llava":case"paligemma":t=Qa(n.text_config);break;case"moondream1":t=Qa(n.phi_config);break;case"musicgen":t=Qa(n.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":e.num_heads="num_attention_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size",e.num_attention_heads="num_attention_heads";break;case"gemma":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="head_dim";break;case"openelm":e.num_heads="num_kv_heads",e.num_layers="num_transformer_layers",e.dim_kv="head_dim";break;case"gpt_neo":e.num_heads="num_heads",e.num_layers="num_layers",e.hidden_size="hidden_size";break;case"bloom":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="hidden_size";break;case"mpt":e.num_heads="n_heads",e.num_layers="n_layers",e.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":e.num_decoder_layers="num_decoder_layers",e.num_decoder_heads="num_heads",e.decoder_dim_kv="d_kv",e.num_encoder_layers="num_layers",e.num_encoder_heads="num_heads",e.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="d_model",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="d_model";break;case"speecht5":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="hidden_size",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="hidden_size";break;case"trocr":e.num_encoder_layers=e.num_decoder_layers="decoder_layers",e.num_encoder_heads=e.num_decoder_heads="decoder_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="d_model";break;case"musicgen_decoder":e.num_encoder_layers=e.num_decoder_layers="num_hidden_layers",e.num_encoder_heads=e.num_decoder_heads="num_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const i=Qa(n.encoder),a=Qa(n.decoder),s="num_decoder_layers"in a,o={};return s?(o.num_decoder_layers=a.num_layers,o.num_decoder_heads=a.num_heads,o.decoder_hidden_size=a.hidden_size,o.num_encoder_layers=i.num_layers,o.num_encoder_heads=i.num_heads,o.encoder_hidden_size=i.hidden_size):(o.num_layers=a.num_layers,o.num_heads=a.num_heads,o.hidden_size=a.hidden_size),o}const r={...t,...oa(n,["model_type","multi_query","is_encoder_decoder"])};for(const i in e)r[i]=n[e[i]];return r}function kw(n,{prefix:e="past_key_values",encoder_add_pkv:t=!0}={}){const r={},i=n.normalized_config,a=1;if(i.is_encoder_decoder&&t){const s=i.encoder_dim_kv??i.encoder_hidden_size/i.num_encoder_heads,o=i.decoder_dim_kv??i.decoder_hidden_size/i.num_decoder_heads,l=[a,i.num_encoder_heads,0,s],u=[a,i.num_decoder_heads,0,o];for(let c=0;c=1&&s[s.length-1]>=this.timestamp_begin,l=s.length<2||s[s.length-2]>=this.timestamp_begin;if(o&&(l?a.subarray(this.timestamp_begin).fill(-1/0):a.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const p=this.timestamp_begin+this.max_initial_timestamp_index;a.subarray(p+1).fill(-1/0)}const u=T1(a),c=Math.log(u.subarray(this.timestamp_begin).map(Math.exp).reduce((p,d)=>p+d)),h=wr(u.subarray(0,this.timestamp_begin))[0];c>h&&a.subarray(0,this.timestamp_begin).fill(-1/0)}return t}}class zM extends Zr{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let a=0;a1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,i=t.slice([0,r],null),a=t.slice([r,t.dims[0]],null);for(let s=0;s1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(r)||r<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${r}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=r}}class HM extends Bd{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,r),this.filter_value=t}}class Dw{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,oa(e,Object.getOwnPropertyNames(this)))}}class Fd extends Nn{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}}class Gd extends Nn{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof Gd?e=e.criteria:e instanceof Fd&&(e=[e]),this.criteria.push(...e)}_call(e,t){const r=new Array(e.length).fill(!1);for(const i of this.criteria){const a=i(e,t);for(let s=0;st.length>=this.max_length)}}class jM extends Fd{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const i=r.at(-1);return this.eos_token_id.some(a=>i==a)})}}class nu extends Nn{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),i=e.data;if(t===-1)i=i.slice(-r);else{let a=t*r;i=i.slice(a,a+r)}return i}randomSelect(e){let t=0;for(let i=0;i1)return new KM(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new XM(e)}}class XM extends nu{async sample(e){const t=wr(e.data)[1];return[[BigInt(t),0]]}}class YM extends nu{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,i]=await gs(e,t),a=zn(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const s=this.randomSelect(a);return[i.data[s],Math.log(a[s])]})}}class KM extends nu{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,i]=await gs(e,t),a=zn(r.data);return Array.from({length:this.generation_config.num_beams},(s,o)=>[i.data[o],Math.log(a[o])])}}class ZM extends Dw{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}const _t={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},Vl=new Map,Lw=new Map,Ws=new Map;async function QM(n,e,t){let r=t.device;r&&typeof r!="string"&&(r.hasOwnProperty(e)?r=r[e]:(console.warn(`Device not specified for ${e}. Using the default device.`),r=null));const i=uS(r);let a=t.dtype;if(typeof a!="string"&&(a&&a.hasOwnProperty(e)?a=a[e]:(a=PM[i[0]],console.warn(`Dtype not specified for ${e}. Using the default dtype: ${a}.`))),ig.hasOwnProperty(a)){if(a===nr.fp16&&!await IM())throw new Error("The device does not support fp16.")}else throw new Error(`Invalid dtype: ${a}. Should be one of: ${Object.keys(nr).join(", ")}`);const s=ig[a],o=`${t.subfolder??""}/${e}${s}.onnx`,l={...t.session_options};l.executionProviders??=i;const u=vl(n,o,!0,t);let c=[];if(t.use_external_data_format){if(pa.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const p=`${e}${s}.onnx_data`,d=`${t.subfolder??""}/${p}`;c.push(new Promise(async(m,y)=>{const g=await vl(n,d,!0,t);m({path:p,data:g})}))}else l.externalData!==void 0&&(c=l.externalData.map(async p=>{if(typeof p.data=="string"){const d=await vl(n,p.data,!0,t);return{...p,data:d}}return p}));if(c.length>0&&(l.externalData=await Promise.all(c)),r==="webgpu"){const p=kw(t.config,{prefix:"present"});if(Object.keys(p).length>0){const d={};for(const m in p)d[m]="gpu-buffer";l.preferredOutputLocation=d}}return{buffer:await u,session_options:l}}async function ji(n,e,t){const r=Object.keys(e),i=await Promise.all(r.map(async s=>QM(n,e[s],t))),a={};for(let s=0;s0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const i=Object.keys(e).length,a=n.inputNames.length;if(i>a){let s=Object.keys(e).filter(o=>!n.inputNames.includes(o));console.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${s.join(", ")}".`)}return t}async function Ni(n,e){const t=JM(n,e);try{const r=Object.fromEntries(Object.entries(t).map(([a,s])=>[a,s.ort_tensor]));let i=await n.run(r);return i=zw(i),i}catch(r){throw console.error(`An error occurred during model execution: "${r}".`),console.error("Inputs given to model:",t),r}}function zw(n){for(let e in n)_w(n[e])?n[e]=new je(n[e]):typeof n[e]=="object"&&zw(n[e]);return n}function Nw(n){if(n instanceof je)return n;if(n.length===0)throw Error("items must be non-empty");if(Array.isArray(n[0])){if(n.some(e=>e.length!==n[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new je("int64",BigInt64Array.from(n.flat().map(e=>BigInt(e))),[n.length,n[0].length])}else return new je("int64",BigInt64Array.from(n.map(e=>BigInt(e))),[1,n.length])}function Uw(n){return new je("bool",[n],[1])}async function ag(n,e){let{encoder_outputs:t,past_key_values:r}=e;if(!t){const l=oa(e,n.sessions.model.inputNames);t=(await Js(n,l)).last_hidden_state}const{input_ids:i,decoder_input_ids:a,...s}=e;return s.input_ids=a,s.encoder_hidden_states=t,n.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(s.encoder_attention_mask=e.attention_mask),await Wd(n,s,!0)}async function Js(n,e){const t=n.sessions.model,r=Object.create(null);for(const i of t.inputNames)r[i]=e[i];return t.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new je("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await Ni(t,r)}async function Wd(n,e,t=!1){const r=n.sessions[t?"decoder_model_merged":"model"],{past_key_values:i,...a}=e;r.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=Uw(!!i)),r.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids&&(a.position_ids=tT(a,i)),n.addPastKeyValues(a,i);const s=oa(a,r.inputNames);return await Ni(r,s)}async function eT(n,{input_ids:e=null,attention_mask:t=null,pixel_values:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:s=null,generation_config:o=null,logits_processor:l=null,...u}){if(!a){if(a=await n.encode_text({input_ids:e}),r&&e.dims[1]!==1){const h=await n.encode_image({pixel_values:r});({inputs_embeds:a,attention_mask:t}=n._merge_input_ids_with_image_features({image_features:h,inputs_embeds:a,input_ids:e,attention_mask:t}))}else if(s&&r&&e.dims[1]===1){const h=e.dims[1],p=Object.values(s)[0].dims.at(-2);t=Xr([oo([e.dims[0],p]),t.slice(null,[t.dims[1]-h,t.dims[1]])],1)}}return await Wd(n,{inputs_embeds:a,past_key_values:s,attention_mask:t,position_ids:i,generation_config:o,logits_processor:l},!0)}function tT(n,e=null){const{input_ids:t,inputs_embeds:r,attention_mask:i}=n,[a,s]=i.dims,o=new BigInt64Array(i.data.length);for(let u=0;ua.dims[1])){if(io==n.config.image_token_index)){const o=n.config.num_image_tokens;if(!o)throw new Error("`num_image_tokens` is missing in the model configuration.");const l=a.dims[1]-(i-o);t.input_ids=a.slice(null,[-l,null]),t.attention_mask=oo([1,i+l])}}}return t}function nT(n,e,t,r){const{...i}=t;return t.past_key_values&&(e=e.map(s=>[s.at(-1)])),i.decoder_input_ids=Nw(e),i}class $e extends Nn{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t){super(),this.config=e,this.sessions=t;const r=Ws.get(this.constructor),i=Vl.get(r);this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,i===_t.DecoderOnly?(this.can_generate=!0,this._forward=Wd,this._prepare_inputs_for_generation=sg):i===_t.Seq2Seq||i===_t.Vision2Seq||i===_t.Musicgen?(this.can_generate=!0,this._forward=ag,this._prepare_inputs_for_generation=nT):i===_t.EncoderDecoder?this._forward=ag:i===_t.ImageTextToText?(this.can_generate=!0,this._forward=eT,this._prepare_inputs_for_generation=sg):this._forward=Js,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))t?.handler?.dispose&&e.push(t.handler.dispose());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:c=null,use_external_data_format:h=null,session_options:p={}}={}){let d={progress_callback:t,config:r,cache_dir:i,local_files_only:a,revision:s,model_file_name:o,subfolder:l,device:u,dtype:c,use_external_data_format:h,session_options:p};const m=Ws.get(this),y=Vl.get(m);d.config=await Ow.from_pretrained(e,d);let g;return y===_t.DecoderOnly?g=await Promise.all([ji(e,{model:d.model_file_name??"model"},d),Ii(e,"generation_config.json",!1,d)]):y===_t.Seq2Seq||y===_t.Vision2Seq?g=await Promise.all([ji(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},d),Ii(e,"generation_config.json",!1,d)]):y===_t.MaskGeneration?g=await Promise.all([ji(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},d)]):y===_t.EncoderDecoder?g=await Promise.all([ji(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},d)]):y===_t.ImageTextToText?g=await Promise.all([ji(e,{embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"},d),Ii(e,"generation_config.json",!1,d)]):y===_t.Musicgen?g=await Promise.all([ji(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},d),Ii(e,"generation_config.json",!1,d)]):(y!==_t.EncoderOnly&&console.warn(`Model type for '${m??r?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),g=await Promise.all([ji(e,{model:d.model_file_name??"model"},d)])),new this(d.config,...g)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_warper(e){const t=new ed;return e.temperature!==null&&e.temperature!==1&&t.push(new WM(e.temperature)),e.top_k!==null&&e.top_k!==0&&t.push(new HM(e.top_k)),e.top_p!==null&&e.top_p<1&&t.push(new VM(e.top_p)),t}_get_logits_processor(e,t,r=null){const i=new ed;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&i.push(new NM(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&i.push(new zM(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&i.push(new FM(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&i.push(new UM(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&i.push(new BM(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&i.push(new kM(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&i.push(new OM(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){const a=t>1||e.forced_bos_token_id===null?t:t+1;i.push(new DM(e.begin_suppress_tokens,a))}return e.guidance_scale!==null&&e.guidance_scale>1&&i.push(new GM(e.guidance_scale)),r!==null&&i.extend(r),i}_prepare_generation_config(e,t,r=Dw){const i={...this.config};for(const s of["decoder","generator","text_config"])s in i&&Object.assign(i,i[s]);const a=new r(i);return"generation_config"in this&&Object.assign(a,this.generation_config),e&&Object.assign(a,e),t&&Object.assign(a,oa(t,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(e,t=null){const r=new Gd;return e.max_length!==null&&r.push(new qM(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new jM(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){const e=[Zd,Qd,Kd,Yd],t=Ws.get(this.constructor),r=new Set,i=this.config.model_type;for(const s of e){const o=s.get(i);o&&r.add(o[0])}let a=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw r.size>0&&(a+=` Please use the following class instead: ${[...r].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...e){return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:r,is_encoder_decoder:i}){return r.past_key_values=this.getPastKeyValues(t,r.past_key_values),r.input_ids=new je("int64",e.flat(),[e.length,1]),i||(r.attention_mask=Xr([r.attention_mask,oo([r.attention_mask.dims[0],1])],1)),r.position_ids=null,r}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:r}){const i=oa(r,this.forward_params),a=this.main_input_name;if(a in i){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else i[a]=e;return{inputs_tensor:i[a],model_inputs:i,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:r,generation_config:i}){const a=oa(t,this.sessions.model.inputNames);let{last_hidden_state:s}=await Js(this,a);return i.guidance_scale!==null&&i.guidance_scale>1&&(s=Xr([s,vS(s,0)],0),"attention_mask"in t&&(t.attention_mask=Xr([t.attention_mask,xS(t.attention_mask)],0))),t.encoder_outputs=s,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:r,decoder_start_token_id:i,bos_token_id:a,generation_config:s}){let{decoder_input_ids:o,...l}=r;if(!o)if(i??=a,this.config.model_type==="musicgen")o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[i]);else if(Array.isArray(i)){if(i.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${i.length}`);o=i}else o=Array.from({length:e},()=>[i]);return o=Nw(o),r.decoder_attention_mask=wS(o),{input_ids:o,model_inputs:l}}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:i=null,streamer:a=null,...s}){this._validate_model_class(),t=this._prepare_generation_config(t,s);let{inputs_tensor:o,model_inputs:l,model_input_name:u}=this._prepare_model_inputs({inputs:e,model_kwargs:s});const c=this.config.is_encoder_decoder;c&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:l,model_input_name:u,generation_config:t})));let h;c?{input_ids:h,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[u].dims.at(0),model_input_name:u,model_kwargs:l,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):h=l[u];let p=h.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=p+t.max_new_tokens);const d=this._get_logits_processor(t,p,r),m=this._get_stopping_criteria(t,i),y=l[u].dims.at(0),g=nu.getSampler(t),_=new Array(y).fill(0),w=h.tolist();a&&a.put(w);let b=null;for(;;){l=this.prepare_inputs_for_generation(w,l,t);const T=await this.forward(l),I=T.logits.slice(null,-1,null),C=d(w,I),B=[];for(let k=0;kk)){t.return_dict_in_generate&&(b=this.getPastKeyValues(T,l.past_key_values,!1));break}l=this._update_model_kwargs_for_generation({generated_input_ids:B,outputs:T,model_inputs:l,is_encoder_decoder:c})}a&&a.end();const E=new je("int64",w.flat(),[w.length,w[0].length]);return t.return_dict_in_generate?{sequences:E,past_key_values:b}:E}addAttentionsToBeam(e,t){if(this.config.is_encoder_decoder){if(!t.cross_attentions||t.cross_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.cross_attentions||(e.cross_attentions=[]),e.cross_attentions.push(t.cross_attentions)}if(!t.decoder_attentions||t.decoder_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.decoder_attentions||(e.decoder_attentions=[]),e.decoder_attentions.push(t.decoder_attentions)}groupBeams(e){const t=Object.create(null);for(const r of e)t[r.id]===void 0?t[r.id]=[r]:t[r.id].push(r);return Object.values(t)}getPastKeyValues(e,t,r=!0){const i=Object.create(null);for(const a in e)if(a.startsWith("present")){let s=a.replace("present","past_key_values");if(t&&a.includes("encoder"))i[s]=t[s];else{if(r&&t){const o=t[s];o.location==="gpu-buffer"&&o.dispose()}i[s]=e[a]}}return i}getAttentions(e){const t=Object.create(null);for(const r of["cross_attentions","decoder_attentions"]){const i=[];for(const a in e)if(a.startsWith(r)){const s=a.split(".").pop();i[s]=e[a]}t[r]=i}return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const r=this.custom_config.kv_cache_dtype??"float32",i=r==="float16"?new Uint16Array:[],a=kw(this.config);for(const s in a)e[s]=new je(r,i,a[s])}}}class br{}class co extends $e{}class rT extends co{}class iT extends co{async _call(e){return new Bn(await super._call(e))}}class aT extends co{async _call(e){return new Nt(await super._call(e))}}class sT extends co{async _call(e){return new Un(await super._call(e))}}class oT extends co{async _call(e){return new Yn(await super._call(e))}}class lT extends $e{}class uT extends lT{}class ho extends $e{}class cT extends ho{}class dT extends ho{async _call(e){return new Bn(await super._call(e))}}class hT extends ho{async _call(e){return new Nt(await super._call(e))}}class pT extends ho{async _call(e){return new Un(await super._call(e))}}class fT extends ho{async _call(e){return new Yn(await super._call(e))}}class po extends $e{}class mT extends po{}class gT extends po{async _call(e){return new Bn(await super._call(e))}}class _T extends po{async _call(e){return new Nt(await super._call(e))}}class yT extends po{async _call(e){return new Un(await super._call(e))}}class vT extends po{async _call(e){return new Yn(await super._call(e))}}class fo extends $e{}class wT extends fo{}class bT extends fo{async _call(e){return new Bn(await super._call(e))}}class xT extends fo{async _call(e){return new Nt(await super._call(e))}}class ST extends fo{async _call(e){return new Un(await super._call(e))}}class ET extends fo{async _call(e){return new Yn(await super._call(e))}}class mo extends $e{}class MT extends mo{}class TT extends mo{async _call(e){return new Bn(await super._call(e))}}class AT extends mo{async _call(e){return new Nt(await super._call(e))}}class CT extends mo{async _call(e){return new Un(await super._call(e))}}class $T extends mo{async _call(e){return new Yn(await super._call(e))}}class go extends $e{}class RT extends go{}class IT extends go{async _call(e){return new Bn(await super._call(e))}}class PT extends go{async _call(e){return new Nt(await super._call(e))}}class kT extends go{async _call(e){return new Un(await super._call(e))}}class OT extends go{async _call(e){return new Yn(await super._call(e))}}class _o extends $e{}class DT extends _o{}class LT extends _o{async _call(e){return new Bn(await super._call(e))}}class zT extends _o{async _call(e){return new Nt(await super._call(e))}}class NT extends _o{async _call(e){return new Un(await super._call(e))}}class UT extends _o{async _call(e){return new Yn(await super._call(e))}}class yo extends $e{}class BT extends yo{}class FT extends yo{async _call(e){return new Nt(await super._call(e))}}class GT extends yo{async _call(e){return new Un(await super._call(e))}}class WT extends yo{async _call(e){return new Yn(await super._call(e))}}class VT extends yo{async _call(e){return new Bn(await super._call(e))}}class ru extends $e{}class HT extends ru{}class qT extends ru{async _call(e){return new Bn(await super._call(e))}}class jT extends ru{async _call(e){return new Nt(await super._call(e))}}class XT extends ru{async _call(e){return new Un(await super._call(e))}}class iu extends $e{}class YT extends iu{}class KT extends iu{async _call(e){return new Bn(await super._call(e))}}class ZT extends iu{async _call(e){return new Nt(await super._call(e))}}class QT extends iu{async _call(e){return new Yn(await super._call(e))}}class vo extends $e{}class JT extends vo{}class eA extends vo{async _call(e){return new Bn(await super._call(e))}}class tA extends vo{async _call(e){return new Nt(await super._call(e))}}class nA extends vo{async _call(e){return new Un(await super._call(e))}}class rA extends vo{async _call(e){return new Yn(await super._call(e))}}class au extends $e{}class iA extends au{}class aA extends au{async _call(e){return new Bn(await super._call(e))}}class sA extends au{async _call(e){return new Nt(await super._call(e))}}class oA extends au{async _call(e){return new Yn(await super._call(e))}}class su extends $e{}class lA extends su{}class uA extends su{async _call(e){return new Nt(await super._call(e))}}class cA extends su{async _call(e){return new Yn(await super._call(e))}}class dA extends su{async _call(e){return new Bn(await super._call(e))}}class Bw extends $e{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(e,t,r){super(e,t),this.generation_config=r}}class hA extends Bw{}class pA extends Bw{}class Fw extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class fA extends Fw{}class mA extends Fw{}class Gw extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class gA extends Gw{}class _A extends Gw{}class Vd extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class yA extends Vd{}class vA extends Vd{}class wA extends Vd{async _call(e){return new Nt(await super._call(e))}}class ou extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class bA extends ou{}class xA extends ou{}class SA extends ou{async _call(e){return new Nt(await super._call(e))}}class EA extends ou{}class Ww extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class MA extends Ww{}class TA extends Ww{}class Vw extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class AA extends Vw{}class CA extends Vw{}class wo extends $e{}class $A extends wo{}class RA extends wo{async _call(e){return new Bn(await super._call(e))}}class IA extends wo{async _call(e){return new Nt(await super._call(e))}}class PA extends wo{async _call(e){return new Un(await super._call(e))}}class kA extends wo{async _call(e){return new Yn(await super._call(e))}}class bo extends $e{}class OA extends bo{}class DA extends bo{async _call(e){return new Bn(await super._call(e))}}class LA extends bo{async _call(e){return new Nt(await super._call(e))}}class zA extends bo{async _call(e){return new Un(await super._call(e))}}class NA extends bo{async _call(e){return new Yn(await super._call(e))}}class xo extends $e{}class UA extends xo{}class BA extends xo{async _call(e){return new Bn(await super._call(e))}}class FA extends xo{async _call(e){return new Nt(await super._call(e))}}class GA extends xo{async _call(e){return new Un(await super._call(e))}}class WA extends xo{async _call(e){return new Yn(await super._call(e))}}class Hw extends $e{}class VA extends Hw{}class HA extends Hw{}class qw extends $e{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(e,t,r){super(e,t),this.generation_config=r}}class qA extends qw{}class jA extends qw{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,ZM)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const i=e.task;if(e.is_multilingual){r||(console.warn("No language specified - defaulting to English (en)."),r="en");const s=`<|${ww(r)}|>`;t.push(e.lang_to_id[s]),t.push(e.task_to_id[i??"transcribe"])}else if(r||i)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(a=>a!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:i=null,...a}){t=this._prepare_generation_config(t,a);const s=this._retrieve_init_tokens(t);return t.return_timestamps&&(r??=new ed,r.push(new LM(t,s))),await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:s,...a})}_extract_token_timestamps(e,t,r=null,i=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");let a=this.config.median_filter_width;a===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const s=e.cross_attentions.map(u=>{let c=Array.from({length:this.config.decoder_layers},(g,_)=>Xr(u.map(w=>w[_]),2)),h=Zs(t.map(([g,_])=>r?c[g].slice(null,_,null,[0,r]):c[g].slice(null,_)));h=h.transpose(1,0,2,3);let[p,d]=mS(h,-2,0,!0),m=h.clone();for(let g=0;gh[_+1]-h[_]),m=Cn([1],d).map(g=>!!g),y=[];for(let g=0;gp.findIndex(d=>d==a)),l=o.every(p=>p===-1),u=o.every(p=>p!==-1);if(!l&&!u)throw new Error("Every input should contain either 0 or 1 image token.");if(l)return{inputs_embeds:e,attention_mask:i};const c=[],h=[];for(let p=0;pa*s,1);e.input_labels=new je("int64",new BigInt64Array(i).fill(1n),r)}const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await Ni(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new O$(await super._call(e))}}class O$ extends br{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class Pb extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class D$ extends Pb{}class L$ extends Pb{}class kb extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class z$ extends kb{}class N$ extends kb{}class xa extends $e{}class U$ extends xa{}class B$ extends xa{async _call(e){return new ys(await super._call(e))}}class F$ extends xa{async _call(e){return new Nt(await super._call(e))}}class G$ extends xa{async _call(e){return new Un(await super._call(e))}}class qd extends $e{}class W$ extends qd{}class V$ extends qd{async _call(e){return new ys(await super._call(e))}}class H$ extends qd{async _call(e){return new Nt(await super._call(e))}}class uu extends $e{}class q$ extends uu{}class j$ extends uu{async _call(e){return new ys(await super._call(e))}}class X$ extends uu{async _call(e){return new Nt(await super._call(e))}}class Y$ extends uu{async _call(e){return new Un(await super._call(e))}}class jd extends $e{}class K$ extends jd{}class Z$ extends jd{async _call(e){return new ys(await super._call(e))}}class Q$ extends jd{async _call(e){return new Nt(await super._call(e))}}class J$ extends xa{}class e3 extends xa{async _call(e){return new ys(await super._call(e))}}class t3 extends xa{async _call(e){return new Nt(await super._call(e))}}class So extends $e{}class n3 extends So{}class r3 extends So{async _call(e){return new ys(await super._call(e))}}class i3 extends So{async _call(e){return new Nt(await super._call(e))}}class a3 extends So{async _call(e){return new rR(await super._call(e))}}class s3 extends So{async _call(e){return new Un(await super._call(e))}}class Ob extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class o3 extends Ob{}class l3 extends Ob{async generate_speech(e,t,{threshold:r=.5,minlenratio:i=0,maxlenratio:a=20,vocoder:s=null}={}){const o={input_ids:e},{encoder_outputs:l,encoder_attention_mask:u}=await Js(this,o),c=l.dims[1]/this.config.reduction_factor,h=Math.floor(c*a),p=Math.floor(c*i),d=this.config.num_mel_bins;let m=[],y=null,g=null,_=0;for(;;){++_;const E=Uw(!!g);let T;g?T=g.output_sequence_out:T=new je("float32",new Float32Array(d),[1,1,d]);let I={use_cache_branch:E,output_sequence:T,encoder_attention_mask:u,speaker_embeddings:t,encoder_hidden_states:l};this.addPastKeyValues(I,y),g=await Ni(this.sessions.decoder_model_merged,I),y=this.getPastKeyValues(g,y);const{prob:C,spectrum:B}=g;if(m.push(B),_>=p&&(Array.from(C.data).filter(R=>R>=r).length>0||_>=h))break}const w=Xr(m),{waveform:b}=await Ni(s.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:b}}}class u3 extends $e{main_input_name="spectrogram"}class c3 extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class d3 extends c3{}class Db extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class h3 extends Db{}class p3 extends Db{}class Lb extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class f3 extends Lb{}class m3 extends Lb{}class zb extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class g3 extends zb{}class _3 extends zb{}class Xd extends $e{}class y3 extends Xd{}class v3 extends Xd{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class w3 extends Xd{static async from_pretrained(e,t={}){return t.model_file_name??="audio_model",super.from_pretrained(e,t)}}class b3 extends $e{}class Nb extends b3{async _call(e){return new aR(await super._call(e))}}class Ub extends $e{}class x3 extends Ub{}class S3 extends Ub{}class Bb extends $e{constructor(e,t,r){super(e,t),this.generation_config=r}}class E3 extends Bb{}class M3 extends Bb{}class Fb extends $e{}class T3 extends Fb{}class A3 extends Fb{async _call(e){return new Nt(await super._call(e))}}class Gb extends $e{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(e,t,r){super(e,t),this.generation_config=r}_apply_and_filter_by_delay_pattern_mask(e){const[t,r]=e.dims,i=this.config.decoder.num_codebooks,a=r-i;let s=0;for(let u=0;u0&&p<=a&&(e.data[s++]=e.data[u])}const o=Math.floor(t/i),l=s/(o*i);return new je(e.type,e.data.slice(0,s),[o,i,l])}prepare_inputs_for_generation(e,t,r){let i=structuredClone(e);for(let s=0;s=o&&(i[s][o]=BigInt(this.config.decoder.pad_token_id));return r.guidance_scale!==null&&r.guidance_scale>1&&(i=i.concat(i)),super.prepare_inputs_for_generation(i,t,r)}async generate(e){const t=await super.generate(e),r=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:i}=await Ni(this.sessions.encodec_decode,{audio_codes:r});return i}}class cn{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:c=null,use_external_data_format:h=null,session_options:p={}}={}){let d={progress_callback:t,config:r,cache_dir:i,local_files_only:a,revision:s,model_file_name:o,subfolder:l,device:u,dtype:c,use_external_data_format:h,session_options:p};if(d.config=await Ow.from_pretrained(e,d),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let m of this.MODEL_CLASS_MAPPINGS){const y=m.get(d.config.model_type);if(y)return await y[1].from_pretrained(e,d)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${d.config.model_type}", attempting to construct from base class.`),await $e.from_pretrained(e,d);throw Error(`Unsupported model type: ${d.config.model_type}`)}}const C3=new Map([["bert",["BertModel",rT]],["nomic_bert",["NomicBertModel",uT]],["roformer",["RoFormerModel",cT]],["electra",["ElectraModel",wT]],["esm",["EsmModel",HT]],["convbert",["ConvBertModel",mT]],["camembert",["CamembertModel",MT]],["deberta",["DebertaModel",RT]],["deberta-v2",["DebertaV2Model",DT]],["mpnet",["MPNetModel",JT]],["albert",["AlbertModel",lA]],["distilbert",["DistilBertModel",BT]],["roberta",["RobertaModel",$A]],["xlm",["XLMModel",OA]],["xlm-roberta",["XLMRobertaModel",UA]],["clap",["ClapModel",y3]],["clip",["CLIPModel",KA]],["clipseg",["CLIPSegModel",iC]],["chinese_clip",["ChineseCLIPModel",rC]],["siglip",["SiglipModel",JA]],["mobilebert",["MobileBertModel",YT]],["squeezebert",["SqueezeBertModel",iA]],["wav2vec2",["Wav2Vec2Model",U$]],["wav2vec2-bert",["Wav2Vec2BertModel",K$]],["unispeech",["UniSpeechModel",W$]],["unispeech-sat",["UniSpeechSatModel",q$]],["hubert",["HubertModel",J$]],["wavlm",["WavLMModel",n3]],["audio-spectrogram-transformer",["ASTModel",VA]],["vits",["VitsModel",Nb]],["detr",["DetrModel",e$]],["table-transformer",["TableTransformerModel",i$]],["vit",["ViTModel",NC]],["fastvit",["FastViTModel",BC]],["mobilevit",["MobileViTModel",VC]],["mobilevitv2",["MobileViTV2Model",qC]],["owlvit",["OwlViTModel",XC]],["owlv2",["Owlv2Model",KC]],["beit",["BeitModel",QC]],["deit",["DeiTModel",o$]],["convnext",["ConvNextModel",S$]],["convnextv2",["ConvNextV2Model",M$]],["dinov2",["Dinov2Model",A$]],["resnet",["ResNetModel",u$]],["swin",["SwinModel",d$]],["swin2sr",["Swin2SRModel",p$]],["donut-swin",["DonutSwinModel",x$]],["yolos",["YolosModel",$$]],["dpt",["DPTModel",m$]],["glpn",["GLPNModel",v$]],["hifigan",["SpeechT5HifiGan",u3]],["efficientnet",["EfficientNetModel",T3]]]),$3=new Map([["t5",["T5Model",hA]],["longt5",["LongT5Model",fA]],["mt5",["MT5Model",gA]],["bart",["BartModel",yA]],["mbart",["MBartModel",bA]],["marian",["MarianModel",D$]],["whisper",["WhisperModel",qA]],["m2m_100",["M2M100Model",z$]],["blenderbot",["BlenderbotModel",MA]],["blenderbot-small",["BlenderbotSmallModel",AA]]]),R3=new Map([["bloom",["BloomModel",PC]],["gpt2",["GPT2Model",sC]],["gptj",["GPTJModel",hC]],["gpt_bigcode",["GPTBigCodeModel",fC]],["gpt_neo",["GPTNeoModel",lC]],["gpt_neox",["GPTNeoXModel",cC]],["codegen",["CodeGenModel",gC]],["llama",["LlamaModel",yC]],["cohere",["CohereModel",wC]],["gemma",["GemmaModel",xC]],["openelm",["OpenELMModel",EC]],["qwen2",["Qwen2Model",TC]],["phi",["PhiModel",CC]],["phi3",["Phi3Model",RC]],["mpt",["MptModel",OC]],["opt",["OPTModel",LC]],["mistral",["MistralModel",h3]],["starcoder2",["Starcoder2Model",f3]],["falcon",["FalconModel",g3]],["stablelm",["StableLmModel",E3]]]),Yd=new Map([["speecht5",["SpeechT5ForSpeechToText",o3]],["whisper",["WhisperForConditionalGeneration",jA]]]),Wb=new Map([["speecht5",["SpeechT5ForTextToSpeech",l3]]]),Vb=new Map([["vits",["VitsModel",Nb]],["musicgen",["MusicgenForConditionalGeneration",Gb]]]),Hb=new Map([["bert",["BertForSequenceClassification",aT]],["roformer",["RoFormerForSequenceClassification",hT]],["electra",["ElectraForSequenceClassification",xT]],["esm",["EsmForSequenceClassification",jT]],["convbert",["ConvBertForSequenceClassification",_T]],["camembert",["CamembertForSequenceClassification",AT]],["deberta",["DebertaForSequenceClassification",PT]],["deberta-v2",["DebertaV2ForSequenceClassification",zT]],["mpnet",["MPNetForSequenceClassification",tA]],["albert",["AlbertForSequenceClassification",uA]],["distilbert",["DistilBertForSequenceClassification",FT]],["roberta",["RobertaForSequenceClassification",IA]],["xlm",["XLMForSequenceClassification",LA]],["xlm-roberta",["XLMRobertaForSequenceClassification",FA]],["bart",["BartForSequenceClassification",wA]],["mbart",["MBartForSequenceClassification",SA]],["mobilebert",["MobileBertForSequenceClassification",ZT]],["squeezebert",["SqueezeBertForSequenceClassification",sA]]]),qb=new Map([["bert",["BertForTokenClassification",sT]],["roformer",["RoFormerForTokenClassification",pT]],["electra",["ElectraForTokenClassification",ST]],["esm",["EsmForTokenClassification",XT]],["convbert",["ConvBertForTokenClassification",yT]],["camembert",["CamembertForTokenClassification",CT]],["deberta",["DebertaForTokenClassification",kT]],["deberta-v2",["DebertaV2ForTokenClassification",NT]],["mpnet",["MPNetForTokenClassification",nA]],["distilbert",["DistilBertForTokenClassification",GT]],["roberta",["RobertaForTokenClassification",PA]],["xlm",["XLMForTokenClassification",zA]],["xlm-roberta",["XLMRobertaForTokenClassification",GA]]]),Kd=new Map([["t5",["T5ForConditionalGeneration",pA]],["longt5",["LongT5ForConditionalGeneration",mA]],["mt5",["MT5ForConditionalGeneration",_A]],["bart",["BartForConditionalGeneration",vA]],["mbart",["MBartForConditionalGeneration",xA]],["marian",["MarianMTModel",L$]],["m2m_100",["M2M100ForConditionalGeneration",N$]],["blenderbot",["BlenderbotForConditionalGeneration",TA]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",CA]]]),Zd=new Map([["bloom",["BloomForCausalLM",kC]],["gpt2",["GPT2LMHeadModel",oC]],["gptj",["GPTJForCausalLM",pC]],["gpt_bigcode",["GPTBigCodeForCausalLM",mC]],["gpt_neo",["GPTNeoForCausalLM",uC]],["gpt_neox",["GPTNeoXForCausalLM",dC]],["codegen",["CodeGenForCausalLM",_C]],["llama",["LlamaForCausalLM",vC]],["cohere",["CohereForCausalLM",bC]],["gemma",["GemmaForCausalLM",SC]],["openelm",["OpenELMForCausalLM",MC]],["qwen2",["Qwen2ForCausalLM",AC]],["phi",["PhiForCausalLM",$C]],["phi3",["Phi3ForCausalLM",IC]],["mpt",["MptForCausalLM",DC]],["opt",["OPTForCausalLM",zC]],["mbart",["MBartForCausalLM",EA]],["mistral",["MistralForCausalLM",p3]],["starcoder2",["Starcoder2ForCausalLM",m3]],["falcon",["FalconForCausalLM",_3]],["trocr",["TrOCRForCausalLM",d3]],["stablelm",["StableLmForCausalLM",M3]]]),jb=new Map([["bert",["BertForMaskedLM",iT]],["roformer",["RoFormerForMaskedLM",dT]],["electra",["ElectraForMaskedLM",bT]],["esm",["EsmForMaskedLM",qT]],["convbert",["ConvBertForMaskedLM",gT]],["camembert",["CamembertForMaskedLM",TT]],["deberta",["DebertaForMaskedLM",IT]],["deberta-v2",["DebertaV2ForMaskedLM",LT]],["mpnet",["MPNetForMaskedLM",eA]],["albert",["AlbertForMaskedLM",dA]],["distilbert",["DistilBertForMaskedLM",VT]],["roberta",["RobertaForMaskedLM",RA]],["xlm",["XLMWithLMHeadModel",DA]],["xlm-roberta",["XLMRobertaForMaskedLM",BA]],["mobilebert",["MobileBertForMaskedLM",KT]],["squeezebert",["SqueezeBertForMaskedLM",aA]]]),Xb=new Map([["bert",["BertForQuestionAnswering",oT]],["roformer",["RoFormerForQuestionAnswering",fT]],["electra",["ElectraForQuestionAnswering",ET]],["convbert",["ConvBertForQuestionAnswering",vT]],["camembert",["CamembertForQuestionAnswering",$T]],["deberta",["DebertaForQuestionAnswering",OT]],["deberta-v2",["DebertaV2ForQuestionAnswering",UT]],["mpnet",["MPNetForQuestionAnswering",rA]],["albert",["AlbertForQuestionAnswering",cA]],["distilbert",["DistilBertForQuestionAnswering",WT]],["roberta",["RobertaForQuestionAnswering",kA]],["xlm",["XLMForQuestionAnswering",NA]],["xlm-roberta",["XLMRobertaForQuestionAnswering",WA]],["mobilebert",["MobileBertForQuestionAnswering",QT]],["squeezebert",["SqueezeBertForQuestionAnswering",oA]]]),Qd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",jw]]]),I3=new Map([["llava",["LlavaForConditionalGeneration",Xw]],["moondream1",["Moondream1ForConditionalGeneration",YA]]]),P3=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",jw]]]),Yb=new Map([["vit",["ViTForImageClassification",UC]],["fastvit",["FastViTForImageClassification",FC]],["mobilevit",["MobileViTForImageClassification",HC]],["mobilevitv2",["MobileViTV2ForImageClassification",jC]],["beit",["BeitForImageClassification",JC]],["deit",["DeiTForImageClassification",l$]],["convnext",["ConvNextForImageClassification",E$]],["convnextv2",["ConvNextV2ForImageClassification",T$]],["dinov2",["Dinov2ForImageClassification",C$]],["resnet",["ResNetForImageClassification",c$]],["swin",["SwinForImageClassification",h$]],["segformer",["SegformerForImageClassification",x3]],["efficientnet",["EfficientNetForImageClassification",A3]]]),Kb=new Map([["detr",["DetrForObjectDetection",t$]],["table-transformer",["TableTransformerForObjectDetection",a$]],["yolos",["YolosForObjectDetection",R$]]]),Zb=new Map([["owlvit",["OwlViTForObjectDetection",YC]],["owlv2",["Owlv2ForObjectDetection",ZC]]]),Qb=new Map([["detr",["DetrForSegmentation",n$]],["clipseg",["CLIPSegForImageSegmentation",aC]]]),Jb=new Map([["segformer",["SegformerForSemanticSegmentation",S3]]]),k3=new Map([["sam",["SamModel",k$]]]),ex=new Map([["wav2vec2",["Wav2Vec2ForCTC",B$]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Z$]],["unispeech",["UniSpeechForCTC",V$]],["unispeech-sat",["UniSpeechSatForCTC",j$]],["wavlm",["WavLMForCTC",r3]],["hubert",["HubertForCTC",e3]]]),tx=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",F$]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Q$]],["unispeech",["UniSpeechForSequenceClassification",H$]],["unispeech-sat",["UniSpeechSatForSequenceClassification",X$]],["wavlm",["WavLMForSequenceClassification",i3]],["hubert",["HubertForSequenceClassification",t3]],["audio-spectrogram-transformer",["ASTForAudioClassification",HA]]]),O3=new Map([["wavlm",["WavLMForXVector",a3]]]),D3=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Y$]],["wavlm",["WavLMForAudioFrameClassification",s3]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",G$]]]),L3=new Map([["vitmatte",["VitMatteForImageMatting",WC]]]),nx=new Map([["swin2sr",["Swin2SRForImageSuperResolution",f$]]]),rx=new Map([["dpt",["DPTForDepthEstimation",g$]],["depth_anything",["DepthAnythingForDepthEstimation",y$]],["glpn",["GLPNForDepthEstimation",w$]]]),ix=new Map([["clip",["CLIPVisionModelWithProjection",QA]],["siglip",["SiglipVisionModel",tC]]]),ax=[[C3,_t.EncoderOnly],[$3,_t.EncoderDecoder],[R3,_t.DecoderOnly],[Hb,_t.EncoderOnly],[qb,_t.EncoderOnly],[Kd,_t.Seq2Seq],[Yd,_t.Seq2Seq],[Zd,_t.DecoderOnly],[jb,_t.EncoderOnly],[Xb,_t.EncoderOnly],[Qd,_t.Vision2Seq],[I3,_t.ImageTextToText],[Yb,_t.EncoderOnly],[Qb,_t.EncoderOnly],[Jb,_t.EncoderOnly],[L3,_t.EncoderOnly],[nx,_t.EncoderOnly],[rx,_t.EncoderOnly],[Kb,_t.EncoderOnly],[Zb,_t.EncoderOnly],[k3,_t.MaskGeneration],[ex,_t.EncoderOnly],[tx,_t.EncoderOnly],[Wb,_t.Seq2Seq],[Vb,_t.EncoderOnly],[O3,_t.EncoderOnly],[D3,_t.EncoderOnly],[ix,_t.EncoderOnly]];for(const[n,e]of ax)for(const[t,r]of n.values())Vl.set(t,e),Ws.set(r,t),Lw.set(t,r);const z3=[["MusicgenForConditionalGeneration",Gb,_t.Musicgen],["CLIPTextModelWithProjection",ZA,_t.EncoderOnly],["SiglipTextModel",eC,_t.EncoderOnly],["ClapTextModelWithProjection",v3,_t.EncoderOnly],["ClapAudioModelWithProjection",w3,_t.EncoderOnly]];for(const[n,e,t]of z3)Vl.set(n,t),Ws.set(e,n),Lw.set(n,e);class Us extends cn{static MODEL_CLASS_MAPPINGS=ax.map(e=>e[0]);static BASE_IF_FAIL=!0}class og extends cn{static MODEL_CLASS_MAPPINGS=[Hb]}class N3 extends cn{static MODEL_CLASS_MAPPINGS=[qb]}class ac extends cn{static MODEL_CLASS_MAPPINGS=[Kd]}class U3 extends cn{static MODEL_CLASS_MAPPINGS=[Yd]}class B3 extends cn{static MODEL_CLASS_MAPPINGS=[Wb]}class F3 extends cn{static MODEL_CLASS_MAPPINGS=[Vb]}class G3 extends cn{static MODEL_CLASS_MAPPINGS=[Zd]}class W3 extends cn{static MODEL_CLASS_MAPPINGS=[jb]}class V3 extends cn{static MODEL_CLASS_MAPPINGS=[Xb]}class H3 extends cn{static MODEL_CLASS_MAPPINGS=[Qd]}class q3 extends cn{static MODEL_CLASS_MAPPINGS=[Yb]}class j3 extends cn{static MODEL_CLASS_MAPPINGS=[Qb]}class X3 extends cn{static MODEL_CLASS_MAPPINGS=[Jb]}class Y3 extends cn{static MODEL_CLASS_MAPPINGS=[Kb]}class K3 extends cn{static MODEL_CLASS_MAPPINGS=[Zb]}class Z3 extends cn{static MODEL_CLASS_MAPPINGS=[ex]}class Q3 extends cn{static MODEL_CLASS_MAPPINGS=[tx]}class J3 extends cn{static MODEL_CLASS_MAPPINGS=[P3]}class eR extends cn{static MODEL_CLASS_MAPPINGS=[nx]}class tR extends cn{static MODEL_CLASS_MAPPINGS=[rx]}class nR extends cn{static MODEL_CLASS_MAPPINGS=[ix]}class Nt extends br{constructor({logits:e}){super(),this.logits=e}}class rR extends br{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class Un extends br{constructor({logits:e}){super(),this.logits=e}}class Bn extends br{constructor({logits:e}){super(),this.logits=e}}class Yn extends br{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class ys extends br{constructor({logits:e}){super(),this.logits=e}}class iR extends br{constructor({alphas:e}){super(),this.alphas=e}}class aR extends br{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}const pr=typeof self<"u",sR=pr&&self.constructor.name==="DedicatedWorkerGlobalScope";let Qi,sx,$i;if(pr)Qi=(n,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(n,e)},$i=self.createImageBitmap,sx=self.ImageData;else if(un)$i=async n=>{const t=(await n.metadata()).channels,{data:r,info:i}=await n.rotate().raw().toBuffer({resolveWithObject:!0}),a=new An(new Uint8ClampedArray(r),i.width,i.height,i.channels);return t!==void 0&&t!==i.channels&&a.convert(t),a};else throw new Error("Unable to load image processing library.");const oR={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},lR=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class An{constructor(e,t,r,i){this.data=e,this.width=t,this.height=r,this.channels=i}get size(){return[this.width,this.height]}static async read(e){if(e instanceof An)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!pr)throw new Error("fromCanvas() is only supported in browser environments.");const r=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new An(r,e.width,e.height,4)}static async fromURL(e){const t=await Il(e);if(t.status!==200)throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);const r=await t.blob();return this.fromBlob(r)}static async fromBlob(e){if(pr){const t=await $i(e),r=Qi(t.width,t.height).getContext("2d");return r.drawImage(t,0,0),new this(r.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}else{const t=un(await e.arrayBuffer());return await $i(t)}}static fromTensor(e,t="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(t==="CHW")e=e.transpose(1,2,0);else if(t!=="HWC")throw new Error(`Unsupported channel format: ${t}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new An(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,r=0;t=0?l=r:c=-r,i>=0?u=i:h=-i,o.drawImage(s,l,u,e,t,c,h,e,t),new An(o.getImageData(0,0,e,t).data,e,t,4).convert(a)}else{let a=this.toSharp();if(r>=0&&i>=0)a=a.extract({left:Math.floor(r),top:Math.floor(i),width:e,height:t});else if(r<=0&&i<=0){const s=Math.floor(-i),o=Math.floor(-r);a=a.extend({top:s,left:o,right:e-this.width-o,bottom:t-this.height-s})}else{let s=[0,0],o=0;i<0?(s[0]=Math.floor(-i),s[1]=t-this.height-s[0]):o=Math.floor(i);let l=[0,0],u=0;r<0?(l[0]=Math.floor(-r),l[1]=e-this.width-l[0]):u=Math.floor(r),a=a.extend({top:s[0],bottom:s[1],left:l[0],right:l[1]}).extract({left:u,top:o,width:e,height:t})}return await $i(a)}}async toBlob(e="image/png",t=1){if(!pr)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new je("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")t=t.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return t}toCanvas(){if(!pr)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),t=Qi(e.width,e.height),r=new sx(e.data,e.width,e.height);return t.getContext("2d").putImageData(r,0,0),t}_update(e,t,r,i=null){return this.data=e,this.width=t,this.height=r,i!==null&&(this.channels=i),this}clone(){return new An(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(pr){if(sR)throw new Error("Unable to save an image from a Web Worker.");const t=e.split(".").pop().toLowerCase(),r=lR.get(t)??"image/png",i=await this.toBlob(r),a=URL.createObjectURL(i),s=document.createElement("a");s.href=a,s.download=e,s.click(),s.remove()}else{if(er.useFS)return await this.toSharp().toFile(e);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(pr)throw new Error("toSharp() is only supported in server-side environments.");return un(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}async function uR(n,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const t=await(await Il(n)).arrayBuffer(),r=new AudioContext({sampleRate:e});typeof e>"u"&&console.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);const i=await r.decodeAudioData(t);let a;if(i.numberOfChannels===2){const s=Math.sqrt(2),o=i.getChannelData(0),l=i.getChannelData(1);a=new Float32Array(o.length);for(let u=0;u2595*Math.log10(1+n/700),kaldi:n=>1127*Math.log(1+n/700),slaney:(n,e=1e3,t=15,r=27/Math.log(6.4))=>n>=e?t+Math.log(n/e)*r:3*n/200};function sc(n,e="htk"){const t=cR[e];if(!t)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof n=="number"?t(n):n.map(r=>t(r))}const dR={htk:n=>700*(10**(n/2595)-1),kaldi:n=>700*(Math.exp(n/1127)-1),slaney:(n,e=1e3,t=15,r=Math.log(6.4)/27)=>n>=t?e*Math.exp(r*(n-t)):200*n/3};function hR(n,e="htk"){const t=dR[e];if(!t)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof n=="number"?t(n):n.map(r=>t(r))}function pR(n,e){const t=Float64Array.from({length:e.length-1},(s,o)=>e[o+1]-e[o]),r=Array.from({length:n.length},()=>new Array(e.length));for(let s=0;snew Array(n.length));for(let s=0;sn+r*a)}function eo(n,e,t,r,i,a=null,s="htk",o=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');const l=sc(t,s),u=sc(r,s),c=ug(l,u,e+2);let h=hR(c,s),p;if(o){const m=i/(n*2);p=sc(Float64Array.from({length:n},(y,g)=>g*m),s),h=c}else p=ug(0,Math.floor(i/2),n);const d=pR(p,h);if(a!==null&&a==="slaney")for(let m=0;mi)throw Error(`frame_length (${t}) may not be larger than fft_length (${i})`);if(E!==t)throw new Error(`Length of the window (${E}) must equal frame_length (${t})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(a===null&&c!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(s){if(o!=="reflect")throw new Error(`pad_mode="${o}" not implemented yet.`);const L=Math.floor((i-1)/2)+1;n=fR(n,L,L)}const T=Math.floor(1+Math.floor((n.length-t)/r)),I=l?Math.floor(i/2)+1:i;let C=T,B=T;_!==null&&(_>T?w&&(B=_):B=C=_);const R=new C1(i),k=new Float64Array(i),j=new Float64Array(R.outputBufferSize),Q=new Float32Array(I*B);for(let L=0;L=1;--K)k[K]-=u*k[K-1];k[0]*=1-u}for(let K=0;KMath.pow(o,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(t&&(s=s.subarray(0,n)),r===null)return s;if(n>r)throw new Error(`Length of the window (${n}) may not be larger than frame_length (${r})`);return s}function _R([n,e,t,r]){return[n-t/2,e-r/2,n+t/2,e+r/2]}function Jd(n,e=.5,t=null,r=!1){const i=n.logits,a=n.pred_boxes,[s,o,l]=i.dims;if(t!==null&&t.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let c=0;ce&&_.push(b)}else{let b=wr(g.data)[1];if(b===l-1||(w=zn(g.data),w[b]T*h[(I+1)%2])),p.boxes.push(E),p.classes.push(b),p.scores.push(w[b])}}u.push(p)}return u}function Eo(n,e){if(!(n instanceof Float32Array||n instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${n?.constructor?.name??typeof n} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function cg(n,e,t=0,r=null){const i=n/e;let a=R1(i)*e;return r!==null&&a>r&&(a=Math.floor(i)*e),aa?u=Math.floor(a*l/i):a>i&&(l=Math.floor(i*u/a)),await e.resize(u,l,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),i=W_(r.data)[0],s=wr(r.data)[0]-i;if(s===0)return e;const o=t/255;let l=r.width,u=r.height,c=0,h=0;const p=r.data;for(let d=0;dthis.preprocess(a)));return{pixel_values:Zs(r.map(a=>a.pixel_values),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}}class yR extends on{post_process_semantic_segmentation(e,t=null){const r=e.logits,i=r.dims[0];if(t!==null&&t.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const a=[];for(let s=0;sp[b]&&(p[b]=w[b],d[b]=_)}const m=new Array(l.dims[0]),y=h.data;for(let _=0;__!==void 0);a.push({segmentation:h,labels:g})}return a}}class lx extends on{}class vR extends lx{}class wR extends on{}class bR extends on{}class ux extends on{}class xR extends ux{}class SR extends on{}class ER extends on{}class cx extends on{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const r=Math.floor(t/this.crop_pct),[i,a]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(i,a,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class MR extends cx{}class TR extends on{}class AR extends on{}class CR extends on{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}}class dx extends on{}class $R extends dx{}class hx extends on{post_process_object_detection(...e){return Jd(...e)}}class RR extends hx{}class IR extends on{}class PR extends on{}class px extends on{pad_image(e,t,r,i={}){const[a,s,o]=t;let l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(o).fill(l));let u=this.image_std;Array.isArray(u)||(u=new Array(o).fill(l));const c=l.map((h,p)=>-h/u[p]);return super.pad_image(e,t,r,{center:!0,constant_values:c,...i})}}class kR extends px{}class OR extends on{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],i=new je("int64",new BigInt64Array(r.reduce((a,s)=>a*s)).fill(1n),r);return{...t,pixel_mask:i}}post_process_object_detection(...e){return Jd(...e)}remove_low_and_no_objects(e,t,r,i){let a=[],s=[],o=[];for(let l=0;lr&&(a.push(c),s.push(d),o.push(h))}return[a,s,o]}check_segment_validity(e,t,r,i=.5,a=.8){let s=[],o=0,l=0;const u=t[r].data;for(let h=0;h=i&&++l;let c=o>0&&l>0;return c&&(c=o/l>a),[c,s]}compute_segments(e,t,r,i,a,s=null,o=null){let[l,u]=o??e[0].dims,c=new je("int32",new Int32Array(l*u),[l,u]),h=[];if(o!==null)for(let g=0;gd[b]&&(p[b]=g,d[b]=w[b])}let m=0;const y=c.data;for(let g=0;gi!==t.dims[a]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new je("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:i=null}={}){const a=await super._call(e);if(t&&(a.input_points=this.reshape_input_points(t,a.original_sizes,a.reshaped_input_sizes)),r){if(!a.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");a.input_labels=this.add_input_labels(r,a.input_points)}return i&&(a.input_boxes=this.reshape_input_points(i,a.original_sizes,a.reshaped_input_sizes,!0)),a}async post_process_masks(e,t,r,{mask_threshold:i=0,binarize:a=!0,pad_size:s=null}={}){const o=[];s=s??this.pad_size;const l=[s.height,s.width];for(let u=0;ui&&(m[y]=1);p=new je("bool",m,p.dims)}o.push(p)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:i=512/1500,points_per_crop:a=32,crop_n_points_downscale_factor:s=1}={}){}}class zR extends on{pad_image(e,t,r,i={}){const[a,s,o]=t;return super.pad_image(e,t,{width:s+(r-s%r)%r,height:a+(r-a%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...i})}}class NR extends on{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=await Promise.all(e.map(s=>this.preprocess(s))),i=await Promise.all(t.map(s=>this.preprocess(s,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Zs(r.map((s,o)=>Xr([s.pixel_values,i[o].pixel_values],0)),0),original_sizes:r.map(s=>s.original_size),reshaped_input_sizes:r.map(s=>s.reshaped_input_size)}}}class UR extends Sa{constructor(e){super(e),this.config.mel_filters??=eo(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=du(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await cu(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),r=t.data,i=wr(r)[0];for(let a=0;athis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),t=e.slice(0,this.config.n_samples)):(t=new Float32Array(this.config.n_samples),t.set(e)),{input_features:(await this._extract_fbank_features(t)).unsqueeze_(0)}}}class BR extends Sa{_zero_mean_unit_var_norm(e){const r=e.reduce((a,s)=>a+s,0)/e.length,i=e.reduce((a,s)=>a+(s-r)**2,0)/e.length;return e.map(a=>(a-r)/Math.sqrt(i+1e-7))}async _call(e){Eo(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const r=[1,t.length];return{input_values:new je("float32",t,r),attention_mask:new je("int64",new BigInt64Array(t.length).fill(1n),r)}}}class FR extends Sa{constructor(e){super(e);const t=this.config.sampling_rate,r=eo(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let i=0;ir*32768),cu(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:i=!0,return_attention_mask:a=!0}={}){Eo(e,"SeamlessM4TFeatureExtractor");let s=await this._extract_fbank_features(e,this.config.max_length);if(i){const[m,y]=s.dims,g=s.data;for(let _=0;_0){const w=new Float32Array(y*(m+_));w.set(g),w.fill(this.config.padding_value,g.length);const b=m+_;s=new je(s.type,w,[b,y]),a&&(o=new je("int64",new BigInt64Array(b),[1,b]),o.data.fill(1n,0,m))}}const[l,u]=s.dims,c=this.config.stride;if(l%c!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${c}).`);const p=s.view(1,Math.floor(l/c),u*c),d={input_features:p};if(a){const m=p.dims[1],y=new BigInt64Array(m);if(o){const g=o.data;for(let _=1,w=0;_0)if(r==="rand_trunc"){const o=Math.floor(Math.random()*(s+1));e=e.subarray(o,o+t),a=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(s<0){let o=new Float64Array(t);if(o.set(e),i==="repeat")for(let l=e.length;lAn.read(e)))}async function Hl(n,e){return Array.isArray(n)||(n=[n]),await Promise.all(n.map(t=>typeof t=="string"||t instanceof URL?uR(t,e):t instanceof Float64Array?new Float32Array(t):t))}function fx(n,e){e&&(n=n.map(s=>s|0));const[t,r,i,a]=n;return{xmin:t,ymin:r,xmax:i,ymax:a}}class dn extends Nn{constructor({task:e,model:t,tokenizer:r=null,processor:i=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=i}async dispose(){await this.model.dispose()}}class KR extends dn{constructor(e){super(e)}async _call(e,{top_k:t=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(r),a=this.model.config.problem_type==="multi_label_classification"?l=>l.sigmoid():l=>new je("float32",zn(l.data),l.dims),s=this.model.config.id2label,o=[];for(const l of i.logits){const u=a(l),c=await gs(u,t),h=c[0].tolist(),d=c[1].tolist().map((m,y)=>({label:s?s[m]:`LABEL_${m}`,score:h[y]}));t===1?o.push(...d):o.push(d)}return Array.isArray(e)||t===1?o:o[0]}}class ZR extends dn{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const r=Array.isArray(e),i=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),s=(await this.model(i)).logits,o=this.model.config.id2label,l=[];for(let u=0;ub==this.tokenizer.sep_token_id);l[h].map((b,E)=>b==1&&(E===0||E>d&&u.findIndex(T=>T==p[E])===-1));const m=a[h].tolist(),y=s[h].tolist();for(let b=1;bE==p[b])!==-1)&&(m[b]=-1/0,y[b]=-1/0);const g=zn(m).map((b,E)=>[b,E]),_=zn(y).map((b,E)=>[b,E]);g[0][0]=0,_[0][0]=0;const w=v1(g,_).filter(b=>b[0][1]<=b[1][1]).map(b=>[b[0][1],b[1][1],b[0][0]*b[1][0]]).sort((b,E)=>E[2]-b[2]);for(let b=0;bm==this.tokenizer.mask_token_id);if(u===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const c=i[o][u],h=await gs(new je("float32",zn(c.data),c.dims),t),p=h[0].tolist(),d=h[1].tolist();a.push(d.map((m,y)=>{const g=l.slice();return g[u]=m,{score:p[y],token:Number(m),token_str:this.tokenizer.model.vocab[m],sequence:this.tokenizer.decode(g,{skip_special_tokens:!0})}}))}return Array.isArray(e)?a:a[0]}}class eh extends dn{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));const r=this.model.config.task_specific_params;r&&r[this.task]&&r[this.task].prefix&&(e=e.map(l=>r[this.task].prefix+l));const i=this.tokenizer,a={padding:!0,truncation:!0};let s;this instanceof mx&&"_build_translation_inputs"in i?s=i._build_translation_inputs(e,a,t):s=i(e,a);const o=await this.model.generate({...s,...t});return i.batch_decode(o,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}}class eI extends eh{_key="summary_text";constructor(e){super(e)}}class mx extends eh{_key="translation_text";constructor(e){super(e)}}class tI extends dn{constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class nI extends dn{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:i=!1}={}){const a=Array.isArray(e);a||(e=[e]),Array.isArray(t)||(t=[t]);const s=t.map(u=>r.replace("{}",u)),o=i||t.length===1,l=[];for(const u of e){const c=[];for(const d of s){const m=this.tokenizer(u,{text_pair:d,padding:!0,truncation:!0}),y=await this.model(m);o?c.push([y.logits.data[this.contradiction_id],y.logits.data[this.entailment_id]]):c.push(y.logits.data[this.entailment_id])}const p=(o?c.map(d=>zn(d)[1]):zn(c)).map((d,m)=>[d,m]).sort((d,m)=>m[0]-d[0]);l.push({sequence:u,labels:p.map(d=>t[d[1]]),scores:p.map(d=>d[0])})}return a?l:l[0]}}class rI extends dn{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:r=!1,quantize:i=!1,precision:a="binary"}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(s);let l=o.last_hidden_state??o.logits??o.token_embeddings;if(t!=="none")if(t==="mean")l=fS(l,s.attention_mask);else if(t==="cls")l=l.slice(null,0);else throw Error(`Pooling method '${t}' not supported.`);return r&&(l=l.normalize(2,-1)),i&&(l=SS(l,a)),l}}class iI extends dn{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const r=await gi(e),{pixel_values:i}=await this.processor(r),a=await this.model({pixel_values:i});let s;if(t){if(!("pooler_output"in a))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");s=a.pooler_output}else s=a.last_hidden_state??a.logits??a.image_embeds;return s}}class aI extends dn{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,i=await Hl(e,r),a=this.model.config.id2label,s=[];for(const o of i){const l=await this.processor(o),c=(await this.model(l)).logits[0],h=await gs(new je("float32",zn(c.data),c.dims),t),p=h[0].tolist(),m=h[1].tolist().map((y,g)=>({label:a?a[y]:`LABEL_${y}`,score:p[g]}));s.push(m)}return Array.isArray(e)?s:s[0]}}class sI extends dn{constructor(e){super(e)}async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){const i=!Array.isArray(e);i&&(e=[e]);const a=t.map(c=>r.replace("{}",c)),s=this.tokenizer(a,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,l=await Hl(e,o),u=[];for(const c of l){const h=await this.processor(c),p=await this.model({...s,...h}),d=zn(p.logits_per_audio.data);u.push([...d].map((m,y)=>({score:m,label:t[y]})))}return i?u[0]:u}}class oI extends dn{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const r=!Array.isArray(e);r&&(e=[e]);const i=this.processor.feature_extractor.config.sampling_rate,a=await Hl(e,i),s=[];for(const o of a){const l=await this.processor(o),c=(await this.model(l)).logits[0],h=[];for(const d of c)h.push(wr(d.data)[1]);const p=this.tokenizer.decode(h);s.push({text:p})}return r?s[0]:s}async _call_whisper(e,t){const r=t.return_timestamps??!1,i=t.chunk_length_s??0,a=t.force_full_sequences??!1;let s=t.stride_length_s??null;r==="word"&&(t.return_token_timestamps=!0);const o=!Array.isArray(e);o&&(e=[e]);const l=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,u=this.processor.feature_extractor.config.hop_length,c=this.processor.feature_extractor.config.sampling_rate,h=await Hl(e,c),p=[];for(const d of h){let m=[];if(i>0){if(s===null)s=i/6;else if(i<=s)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const _=c*i,w=c*s,b=_-2*w;let E=0;for(;E=d.length;m.push({stride:[T.length,C?0:w,B?0:w],input_features:I.input_features,is_last:B}),E+=b}}else m=[{stride:[d.length,0,0],input_features:(await this.processor(d)).input_features,is_last:!0}];for(const _ of m){t.num_frames=Math.floor(_.stride[0]/u);const w=await this.model.generate({inputs:_.input_features,...t});r==="word"?(_.tokens=w.sequences[0].tolist(),_.token_timestamps=w.token_timestamps.tolist()[0].map(b=>wl(b,2))):_.tokens=w[0].tolist(),_.stride=_.stride.map(b=>b/c)}const[y,g]=this.tokenizer._decode_asr(m,{time_precision:l,return_timestamps:r,force_full_sequences:a});p.push({text:y,...g})}return o?p[0]:p}}class lI extends dn{constructor(e){super(e)}async _call(e,t={}){const r=Array.isArray(e),i=await gi(e),{pixel_values:a}=await this.processor(i),s=[];for(const o of a){o.dims=[1,...o.dims];const l=await this.model.generate({inputs:o,...t}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));s.push(u)}return r?s:s[0]}}class uI extends dn{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const r=await gi(e),{pixel_values:i}=await this.processor(r),a=await this.model({pixel_values:i}),s=this.model.config.id2label,o=[];for(const l of a.logits){const u=await gs(new je("float32",zn(l.data),l.dims),t),c=u[0].tolist(),p=u[1].tolist().map((d,m)=>({label:s?s[d]:`LABEL_${d}`,score:c[m]}));o.push(p)}return Array.isArray(e)?o:o[0]}}class cI extends dn{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:i=.8,label_ids_to_fuse:a=null,target_sizes:s=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const u=await gi(e),c=u.map(_=>[_.height,_.width]),{pixel_values:h,pixel_mask:p}=await this.processor(u),d=await this.model({pixel_values:h,pixel_mask:p});let m=null;if(o!==null)m=this.subtasks_mapping[o];else for(let[_,w]of Object.entries(this.subtasks_mapping))if(w in this.processor.feature_extractor){m=this.processor.feature_extractor[w].bind(this.processor.feature_extractor),o=_;break}const y=this.model.config.id2label,g=[];if(o==="panoptic"||o==="instance"){const _=m(d,t,r,i,a,s??c)[0],w=_.segmentation;for(const b of _.segments_info){const E=new Uint8ClampedArray(w.data.length);for(let I=0;Ir.replace("{}",p)),o=this.tokenizer(s,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(a),u=await this.model({...o,pixel_values:l}),c=this.model.config.model_type==="siglip"?p=>p.sigmoid().data:p=>zn(p.data),h=[];for(const p of u.logits_per_image){const m=[...c(p)].map((y,g)=>({score:y,label:t[g]}));m.sort((y,g)=>g.score-y.score),h.push(m)}return i?h:h[0]}}class hI extends dn{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:r=!1}={}){const i=Array.isArray(e);if(i&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const a=await gi(e),s=r?null:a.map(d=>[d.height,d.width]),{pixel_values:o,pixel_mask:l}=await this.processor(a),u=await this.model({pixel_values:o,pixel_mask:l}),c=this.processor.feature_extractor.post_process_object_detection(u,t,s),h=this.model.config.id2label,p=c.map(d=>d.boxes.map((m,y)=>({score:d.scores[y],label:h[d.classes[y]],box:fx(m,!r)})));return i?p:p[0]}}class pI extends dn{constructor(e){super(e)}async _call(e,t,{threshold:r=.1,top_k:i=null,percentage:a=!1}={}){const s=Array.isArray(e),o=await gi(e),l=this.tokenizer(t,{padding:!0,truncation:!0}),u=await this.processor(o),c=[];for(let h=0;h({score:g.scores[b],label:t[g.classes[b]],box:fx(w,!a)})).sort((w,b)=>b.score-w.score);i!==null&&(_=_.slice(0,i)),c.push(_)}return s?c:c[0]}}class fI extends dn{constructor(e){super(e)}async _call(e,t,r={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class mI extends dn{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model(t),i=this.model.config.sampling_rate;return{audio:r.data,sampling_rate:i}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Us.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof t=="string"||t instanceof URL)&&(t=new Float32Array(await(await fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new je("float32",t,[1,t.length]);else if(!(t instanceof je))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:r}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:i}=await this.model.generate_speech(r,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return{audio:i.data,sampling_rate:a}}}class gI extends dn{constructor(e){super(e)}async _call(e){const t=await gi(e),r=await this.processor(t),i=await this.model(r),a=[];for(const s of i.reconstruction){const o=s.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");a.push(An.fromTensor(o))}return a.length>1?a:a[0]}}class _I extends dn{constructor(e){super(e)}async _call(e){const t=await gi(e),r=await this.processor(t),{predicted_depth:i}=await this.model(r),a=[];for(let s=0;s1?a:a[0]}}const dg=Object.freeze({"text-classification":{tokenizer:Tn,pipeline:KR,model:og,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:Tn,pipeline:ZR,model:N3,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:Tn,pipeline:QR,model:V3,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:Tn,pipeline:JR,model:W3,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:Tn,pipeline:eI,model:ac,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:Tn,pipeline:mx,model:ac,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:Tn,pipeline:eh,model:ac,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:Tn,pipeline:tI,model:G3,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:Tn,pipeline:nI,model:og,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:aI,model:Q3,processor:Jn,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:Tn,pipeline:sI,model:Us,processor:Jn,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:Tn,pipeline:oI,model:[U3,Z3],processor:Jn,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:Tn,pipeline:mI,model:[F3,B3],processor:[Jn,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:Tn,pipeline:lI,model:H3,processor:Jn,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:uI,model:q3,processor:Jn,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:cI,model:[j3,X3],processor:Jn,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:Tn,pipeline:dI,model:Us,processor:Jn,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:hI,model:Y3,processor:Jn,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:Tn,pipeline:pI,model:K3,processor:Jn,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:Tn,pipeline:fI,model:J3,processor:Jn,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:gI,model:eR,processor:Jn,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:_I,model:tR,processor:Jn,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:Tn,pipeline:rI,model:Us,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:Jn,pipeline:iI,model:[nR,Us],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),yI=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function vI(n,e=null,{progress_callback:t=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",device:o=null,dtype:l=null,model_file_name:u=null,session_options:c={}}={}){n=yI[n]??n;const h=dg[n.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${n}. Must be one of [${Object.keys(dg)}]`);e||(e=h.default.model,console.log(`No model specified. Using default model: "${e}".`));const p={progress_callback:t,config:r,cache_dir:i,local_files_only:a,revision:s,device:o,dtype:l,model_file_name:u,session_options:c},d=new Map([["tokenizer",h.tokenizer],["model",h.model],["processor",h.processor]]),m=await wI(d,e,p);m.task=n,Za(t,{status:"ready",task:n,model:e});const y=h.pipeline;return new y(m)}async function wI(n,e,t){const r=Object.create(null),i=[];for(let[a,s]of n.entries()){if(!s)continue;let o;Array.isArray(s)?o=new Promise(async(l,u)=>{let c;for(let h of s){if(h===null){l(null);return}try{l(await h.from_pretrained(e,t));return}catch(p){if(p.message?.includes("Unsupported model type"))c=p;else{u(p);return}}}u(c)}):o=s.from_pretrained(e,t),r[a]=o,i.push(o)}await Promise.all(i);for(let[a,s]of Object.entries(r))r[a]=await s;return r}pa.IS_PROCESS_AVAILABLE;/** * @license * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */const th="160",ka={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Oa={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},bI=0,hg=1,xI=2,gx=1,SI=2,li=3,Ui=0,rr=1,qr=2,Oi=0,is=1,pg=2,fg=3,mg=4,EI=5,ra=100,MI=101,TI=102,gg=103,_g=104,AI=200,CI=201,$I=202,RI=203,td=204,nd=205,II=206,PI=207,kI=208,OI=209,DI=210,LI=211,zI=212,NI=213,UI=214,BI=0,FI=1,GI=2,ql=3,WI=4,VI=5,HI=6,qI=7,_x=0,jI=1,XI=2,Di=0,YI=1,KI=2,ZI=3,QI=4,JI=5,eP=6,yx=300,cs=301,ds=302,rd=303,id=304,hu=306,ad=1e3,Lr=1001,sd=1002,qn=1003,yg=1004,lc=1005,mr=1006,tP=1007,to=1008,Li=1009,nP=1010,rP=1011,nh=1012,vx=1013,Pi=1014,ki=1015,no=1016,wx=1017,bx=1018,ua=1020,iP=1021,zr=1023,aP=1024,sP=1025,ca=1026,hs=1027,oP=1028,xx=1029,lP=1030,Sx=1031,Ex=1033,uc=33776,cc=33777,dc=33778,hc=33779,vg=35840,wg=35841,bg=35842,xg=35843,Mx=36196,Sg=37492,Eg=37496,Mg=37808,Tg=37809,Ag=37810,Cg=37811,$g=37812,Rg=37813,Ig=37814,Pg=37815,kg=37816,Og=37817,Dg=37818,Lg=37819,zg=37820,Ng=37821,pc=36492,Ug=36494,Bg=36495,uP=36283,Fg=36284,Gg=36285,Wg=36286,Tx=3e3,da=3001,cP=3200,dP=3201,Ax=0,hP=1,_r="",En="srgb",fi="srgb-linear",rh="display-p3",pu="display-p3-linear",jl="linear",rn="srgb",Xl="rec709",Yl="p3",Da=7680,Vg=519,pP=512,fP=513,mP=514,Cx=515,gP=516,_P=517,yP=518,vP=519,Hg=35044,qg="300 es",od=1035,di=2e3,Kl=2001;class Ea{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const r=this._listeners;r[e]===void 0&&(r[e]=[]),r[e].indexOf(t)===-1&&r[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const r=this._listeners;return r[e]!==void 0&&r[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const i=this._listeners[e];if(i!==void 0){const a=i.indexOf(t);a!==-1&&i.splice(a,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const r=this._listeners[e.type];if(r!==void 0){e.target=this;const i=r.slice(0);for(let a=0,s=i.length;a>8&255]+On[n>>16&255]+On[n>>24&255]+"-"+On[e&255]+On[e>>8&255]+"-"+On[e>>16&15|64]+On[e>>24&255]+"-"+On[t&63|128]+On[t>>8&255]+"-"+On[t>>16&255]+On[t>>24&255]+On[r&255]+On[r>>8&255]+On[r>>16&255]+On[r>>24&255]).toLowerCase()}function Ln(n,e,t){return Math.max(e,Math.min(t,n))}function ih(n,e){return(n%e+e)%e}function wP(n,e,t,r,i){return r+(n-e)*(i-r)/(t-e)}function bP(n,e,t){return n!==e?(t-n)/(e-n):0}function Hs(n,e,t){return(1-t)*n+t*e}function xP(n,e,t,r){return Hs(n,e,1-Math.exp(-t*r))}function SP(n,e=1){return e-Math.abs(ih(n,e*2)-e)}function EP(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function MP(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function TP(n,e){return n+Math.floor(Math.random()*(e-n+1))}function AP(n,e){return n+Math.random()*(e-n)}function CP(n){return n*(.5-Math.random())}function $P(n){n!==void 0&&(jg=n);let e=jg+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function RP(n){return n*Vs}function IP(n){return n*ro}function ld(n){return(n&n-1)===0&&n!==0}function PP(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function Zl(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function kP(n,e,t,r,i){const a=Math.cos,s=Math.sin,o=a(t/2),l=s(t/2),u=a((e+r)/2),c=s((e+r)/2),h=a((e-r)/2),p=s((e-r)/2),d=a((r-e)/2),m=s((r-e)/2);switch(i){case"XYX":n.set(o*c,l*h,l*p,o*u);break;case"YZY":n.set(l*p,o*c,l*h,o*u);break;case"ZXZ":n.set(l*h,l*p,o*c,o*u);break;case"XZX":n.set(o*c,l*m,l*d,o*u);break;case"YXY":n.set(l*d,o*c,l*m,o*u);break;case"ZYZ":n.set(l*m,l*d,o*c,o*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Ja(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function Wn(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const OP={DEG2RAD:Vs,RAD2DEG:ro,generateUUID:ws,clamp:Ln,euclideanModulo:ih,mapLinear:wP,inverseLerp:bP,lerp:Hs,damp:xP,pingpong:SP,smoothstep:EP,smootherstep:MP,randInt:TP,randFloat:AP,randFloatSpread:CP,seededRandom:$P,degToRad:RP,radToDeg:IP,isPowerOfTwo:ld,ceilPowerOfTwo:PP,floorPowerOfTwo:Zl,setQuaternionFromProperEuler:kP,normalize:Wn,denormalize:Ja};class kt{constructor(e=0,t=0){kt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,r=this.y,i=e.elements;return this.x=i[0]*t+i[3]*r+i[6],this.y=i[1]*t+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const r=this.dot(e)/t;return Math.acos(Ln(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y;return t*t+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const r=Math.cos(t),i=Math.sin(t),a=this.x-e.x,s=this.y-e.y;return this.x=a*r-s*i+e.x,this.y=a*i+s*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Lt{constructor(e,t,r,i,a,s,o,l,u){Lt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,r,i,a,s,o,l,u)}set(e,t,r,i,a,s,o,l,u){const c=this.elements;return c[0]=e,c[1]=i,c[2]=o,c[3]=t,c[4]=a,c[5]=l,c[6]=r,c[7]=s,c[8]=u,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],this}extractBasis(e,t,r){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,a=this.elements,s=r[0],o=r[3],l=r[6],u=r[1],c=r[4],h=r[7],p=r[2],d=r[5],m=r[8],y=i[0],g=i[3],_=i[6],w=i[1],b=i[4],E=i[7],T=i[2],I=i[5],C=i[8];return a[0]=s*y+o*w+l*T,a[3]=s*g+o*b+l*I,a[6]=s*_+o*E+l*C,a[1]=u*y+c*w+h*T,a[4]=u*g+c*b+h*I,a[7]=u*_+c*E+h*C,a[2]=p*y+d*w+m*T,a[5]=p*g+d*b+m*I,a[8]=p*_+d*E+m*C,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],c=e[8];return t*s*c-t*o*u-r*a*c+r*o*l+i*a*u-i*s*l}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=c*s-o*u,p=o*l-c*a,d=u*a-s*l,m=t*h+r*p+i*d;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);const y=1/m;return e[0]=h*y,e[1]=(i*u-c*r)*y,e[2]=(o*r-i*s)*y,e[3]=p*y,e[4]=(c*t-i*l)*y,e[5]=(i*a-o*t)*y,e[6]=d*y,e[7]=(r*l-u*t)*y,e[8]=(s*t-r*a)*y,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,r,i,a,s,o){const l=Math.cos(a),u=Math.sin(a);return this.set(r*l,r*u,-r*(l*s+u*o)+s+e,-i*u,i*l,-i*(-u*s+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(fc.makeScale(e,t)),this}rotate(e){return this.premultiply(fc.makeRotation(-e)),this}translate(e,t){return this.premultiply(fc.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,-r,0,r,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,r=e.elements;for(let i=0;i<9;i++)if(t[i]!==r[i])return!1;return!0}fromArray(e,t=0){for(let r=0;r<9;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const fc=new Lt;function $x(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function io(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function DP(){const n=io("canvas");return n.style.display="block",n}const Xg={};function qs(n){n in Xg||(Xg[n]=!0,console.warn(n))}const Yg=new Lt().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),Kg=new Lt().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),Yo={[fi]:{transfer:jl,primaries:Xl,toReference:n=>n,fromReference:n=>n},[En]:{transfer:rn,primaries:Xl,toReference:n=>n.convertSRGBToLinear(),fromReference:n=>n.convertLinearToSRGB()},[pu]:{transfer:jl,primaries:Yl,toReference:n=>n.applyMatrix3(Kg),fromReference:n=>n.applyMatrix3(Yg)},[rh]:{transfer:rn,primaries:Yl,toReference:n=>n.convertSRGBToLinear().applyMatrix3(Kg),fromReference:n=>n.applyMatrix3(Yg).convertLinearToSRGB()}},LP=new Set([fi,pu]),Qt={enabled:!0,_workingColorSpace:fi,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(n){if(!LP.has(n))throw new Error(`Unsupported working color space, "${n}".`);this._workingColorSpace=n},convert:function(n,e,t){if(this.enabled===!1||e===t||!e||!t)return n;const r=Yo[e].toReference,i=Yo[t].fromReference;return i(r(n))},fromWorkingColorSpace:function(n,e){return this.convert(n,this._workingColorSpace,e)},toWorkingColorSpace:function(n,e){return this.convert(n,e,this._workingColorSpace)},getPrimaries:function(n){return Yo[n].primaries},getTransfer:function(n){return n===_r?jl:Yo[n].transfer}};function as(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function mc(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let La;class Rx{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{La===void 0&&(La=io("canvas")),La.width=e.width,La.height=e.height;const r=La.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),t=La}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=io("canvas");t.width=e.width,t.height=e.height;const r=t.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),a=i.data;for(let s=0;s0&&(r.userData=this.userData),t||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==yx)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ad:e.x=e.x-Math.floor(e.x);break;case Lr:e.x=e.x<0?0:1;break;case sd:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ad:e.y=e.y-Math.floor(e.y);break;case Lr:e.y=e.y<0?0:1;break;case sd:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return qs("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===En?da:Tx}set encoding(e){qs("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===da?En:_r}}Xn.DEFAULT_IMAGE=null;Xn.DEFAULT_MAPPING=yx;Xn.DEFAULT_ANISOTROPY=1;class $n{constructor(e=0,t=0,r=0,i=1){$n.prototype.isVector4=!0,this.x=e,this.y=t,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,r,i){return this.x=e,this.y=t,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,a=this.w,s=e.elements;return this.x=s[0]*t+s[4]*r+s[8]*i+s[12]*a,this.y=s[1]*t+s[5]*r+s[9]*i+s[13]*a,this.z=s[2]*t+s[6]*r+s[10]*i+s[14]*a,this.w=s[3]*t+s[7]*r+s[11]*i+s[15]*a,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,r,i,a;const l=e.elements,u=l[0],c=l[4],h=l[8],p=l[1],d=l[5],m=l[9],y=l[2],g=l[6],_=l[10];if(Math.abs(c-p)<.01&&Math.abs(h-y)<.01&&Math.abs(m-g)<.01){if(Math.abs(c+p)<.1&&Math.abs(h+y)<.1&&Math.abs(m+g)<.1&&Math.abs(u+d+_-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const b=(u+1)/2,E=(d+1)/2,T=(_+1)/2,I=(c+p)/4,C=(h+y)/4,B=(m+g)/4;return b>E&&b>T?b<.01?(r=0,i=.707106781,a=.707106781):(r=Math.sqrt(b),i=I/r,a=C/r):E>T?E<.01?(r=.707106781,i=0,a=.707106781):(i=Math.sqrt(E),r=I/i,a=B/i):T<.01?(r=.707106781,i=.707106781,a=0):(a=Math.sqrt(T),r=C/a,i=B/a),this.set(r,i,a,t),this}let w=Math.sqrt((g-m)*(g-m)+(h-y)*(h-y)+(p-c)*(p-c));return Math.abs(w)<.001&&(w=1),this.x=(g-m)/w,this.y=(h-y)/w,this.z=(p-c)/w,this.w=Math.acos((u+d+_-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this.w=e.w+(t.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class UP extends Ea{constructor(e=1,t=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new $n(0,0,e,t),this.scissorTest=!1,this.viewport=new $n(0,0,e,t);const i={width:e,height:t,depth:1};r.encoding!==void 0&&(qs("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),r.colorSpace=r.encoding===da?En:_r),r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:mr,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},r),this.texture=new Xn(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=r.generateMipmaps,this.texture.internalFormat=r.internalFormat,this.depthBuffer=r.depthBuffer,this.stencilBuffer=r.stencilBuffer,this.depthTexture=r.depthTexture,this.samples=r.samples}setSize(e,t,r=1){(this.width!==e||this.height!==t||this.depth!==r)&&(this.width=e,this.height=t,this.depth=r,this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=r,this.dispose()),this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new Ix(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class _a extends UP{constructor(e=1,t=1,r={}){super(e,t,r),this.isWebGLRenderTarget=!0}}class Px extends Xn{constructor(e=null,t=1,r=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:r,depth:i},this.magFilter=qn,this.minFilter=qn,this.wrapR=Lr,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class BP extends Xn{constructor(e=null,t=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:r,depth:i},this.magFilter=qn,this.minFilter=qn,this.wrapR=Lr,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class ya{constructor(e=0,t=0,r=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=r,this._w=i}static slerpFlat(e,t,r,i,a,s,o){let l=r[i+0],u=r[i+1],c=r[i+2],h=r[i+3];const p=a[s+0],d=a[s+1],m=a[s+2],y=a[s+3];if(o===0){e[t+0]=l,e[t+1]=u,e[t+2]=c,e[t+3]=h;return}if(o===1){e[t+0]=p,e[t+1]=d,e[t+2]=m,e[t+3]=y;return}if(h!==y||l!==p||u!==d||c!==m){let g=1-o;const _=l*p+u*d+c*m+h*y,w=_>=0?1:-1,b=1-_*_;if(b>Number.EPSILON){const T=Math.sqrt(b),I=Math.atan2(T,_*w);g=Math.sin(g*I)/T,o=Math.sin(o*I)/T}const E=o*w;if(l=l*g+p*E,u=u*g+d*E,c=c*g+m*E,h=h*g+y*E,g===1-o){const T=1/Math.sqrt(l*l+u*u+c*c+h*h);l*=T,u*=T,c*=T,h*=T}}e[t]=l,e[t+1]=u,e[t+2]=c,e[t+3]=h}static multiplyQuaternionsFlat(e,t,r,i,a,s){const o=r[i],l=r[i+1],u=r[i+2],c=r[i+3],h=a[s],p=a[s+1],d=a[s+2],m=a[s+3];return e[t]=o*m+c*h+l*d-u*p,e[t+1]=l*m+c*p+u*h-o*d,e[t+2]=u*m+c*d+o*p-l*h,e[t+3]=c*m-o*h-l*p-u*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,r,i){return this._x=e,this._y=t,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const r=e._x,i=e._y,a=e._z,s=e._order,o=Math.cos,l=Math.sin,u=o(r/2),c=o(i/2),h=o(a/2),p=l(r/2),d=l(i/2),m=l(a/2);switch(s){case"XYZ":this._x=p*c*h+u*d*m,this._y=u*d*h-p*c*m,this._z=u*c*m+p*d*h,this._w=u*c*h-p*d*m;break;case"YXZ":this._x=p*c*h+u*d*m,this._y=u*d*h-p*c*m,this._z=u*c*m-p*d*h,this._w=u*c*h+p*d*m;break;case"ZXY":this._x=p*c*h-u*d*m,this._y=u*d*h+p*c*m,this._z=u*c*m+p*d*h,this._w=u*c*h-p*d*m;break;case"ZYX":this._x=p*c*h-u*d*m,this._y=u*d*h+p*c*m,this._z=u*c*m-p*d*h,this._w=u*c*h+p*d*m;break;case"YZX":this._x=p*c*h+u*d*m,this._y=u*d*h+p*c*m,this._z=u*c*m-p*d*h,this._w=u*c*h-p*d*m;break;case"XZY":this._x=p*c*h-u*d*m,this._y=u*d*h-p*c*m,this._z=u*c*m+p*d*h,this._w=u*c*h+p*d*m;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,r=t[0],i=t[4],a=t[8],s=t[1],o=t[5],l=t[9],u=t[2],c=t[6],h=t[10],p=r+o+h;if(p>0){const d=.5/Math.sqrt(p+1);this._w=.25/d,this._x=(c-l)*d,this._y=(a-u)*d,this._z=(s-i)*d}else if(r>o&&r>h){const d=2*Math.sqrt(1+r-o-h);this._w=(c-l)/d,this._x=.25*d,this._y=(i+s)/d,this._z=(a+u)/d}else if(o>h){const d=2*Math.sqrt(1+o-r-h);this._w=(a-u)/d,this._x=(i+s)/d,this._y=.25*d,this._z=(l+c)/d}else{const d=2*Math.sqrt(1+h-r-o);this._w=(s-i)/d,this._x=(a+u)/d,this._y=(l+c)/d,this._z=.25*d}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let r=e.dot(t)+1;return rMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ln(this.dot(e),-1,1)))}rotateTowards(e,t){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,t/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const r=e._x,i=e._y,a=e._z,s=e._w,o=t._x,l=t._y,u=t._z,c=t._w;return this._x=r*c+s*o+i*u-a*l,this._y=i*c+s*l+a*o-r*u,this._z=a*c+s*u+r*l-i*o,this._w=s*c-r*o-i*l-a*u,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const r=this._x,i=this._y,a=this._z,s=this._w;let o=s*e._w+r*e._x+i*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=s,this._x=r,this._y=i,this._z=a,this;const l=1-o*o;if(l<=Number.EPSILON){const d=1-t;return this._w=d*s+t*this._w,this._x=d*r+t*this._x,this._y=d*i+t*this._y,this._z=d*a+t*this._z,this.normalize(),this}const u=Math.sqrt(l),c=Math.atan2(u,o),h=Math.sin((1-t)*c)/u,p=Math.sin(t*c)/u;return this._w=s*h+this._w*p,this._x=r*h+this._x*p,this._y=i*h+this._y*p,this._z=a*h+this._z*p,this._onChangeCallback(),this}slerpQuaternions(e,t,r){return this.copy(e).slerp(t,r)}random(){const e=Math.random(),t=Math.sqrt(1-e),r=Math.sqrt(e),i=2*Math.PI*Math.random(),a=2*Math.PI*Math.random();return this.set(t*Math.cos(i),r*Math.sin(a),r*Math.cos(a),t*Math.sin(i))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class re{constructor(e=0,t=0,r=0){re.prototype.isVector3=!0,this.x=e,this.y=t,this.z=r}set(e,t,r){return r===void 0&&(r=this.z),this.x=e,this.y=t,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Zg.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Zg.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,r=this.y,i=this.z,a=e.elements;return this.x=a[0]*t+a[3]*r+a[6]*i,this.y=a[1]*t+a[4]*r+a[7]*i,this.z=a[2]*t+a[5]*r+a[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,a=e.elements,s=1/(a[3]*t+a[7]*r+a[11]*i+a[15]);return this.x=(a[0]*t+a[4]*r+a[8]*i+a[12])*s,this.y=(a[1]*t+a[5]*r+a[9]*i+a[13])*s,this.z=(a[2]*t+a[6]*r+a[10]*i+a[14])*s,this}applyQuaternion(e){const t=this.x,r=this.y,i=this.z,a=e.x,s=e.y,o=e.z,l=e.w,u=2*(s*i-o*r),c=2*(o*t-a*i),h=2*(a*r-s*t);return this.x=t+l*u+s*h-o*c,this.y=r+l*c+o*u-a*h,this.z=i+l*h+a*c-s*u,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,r=this.y,i=this.z,a=e.elements;return this.x=a[0]*t+a[4]*r+a[8]*i,this.y=a[1]*t+a[5]*r+a[9]*i,this.z=a[2]*t+a[6]*r+a[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const r=e.x,i=e.y,a=e.z,s=t.x,o=t.y,l=t.z;return this.x=i*l-a*o,this.y=a*s-r*l,this.z=r*o-i*s,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const r=e.dot(this)/t;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return _c.copy(this).projectOnVector(e),this.sub(_c)}reflect(e){return this.sub(_c.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const r=this.dot(e)/t;return Math.acos(Ln(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return t*t+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,r){const i=Math.sin(t)*e;return this.x=i*Math.sin(r),this.y=Math.cos(t)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,r){return this.x=e*Math.sin(t),this.y=r,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=r,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=(Math.random()-.5)*2,t=Math.random()*Math.PI*2,r=Math.sqrt(1-e**2);return this.x=r*Math.cos(t),this.y=r*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const _c=new re,Zg=new ya;class Mo{constructor(e=new re(1/0,1/0,1/0),t=new re(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,r=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,$r),$r.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,r;return e.normal.x>0?(t=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),t<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ks),Zo.subVectors(this.max,ks),za.subVectors(e.a,ks),Na.subVectors(e.b,ks),Ua.subVectors(e.c,ks),Ei.subVectors(Na,za),Mi.subVectors(Ua,Na),Xi.subVectors(za,Ua);let t=[0,-Ei.z,Ei.y,0,-Mi.z,Mi.y,0,-Xi.z,Xi.y,Ei.z,0,-Ei.x,Mi.z,0,-Mi.x,Xi.z,0,-Xi.x,-Ei.y,Ei.x,0,-Mi.y,Mi.x,0,-Xi.y,Xi.x,0];return!yc(t,za,Na,Ua,Zo)||(t=[1,0,0,0,1,0,0,0,1],!yc(t,za,Na,Ua,Zo))?!1:(Qo.crossVectors(Ei,Mi),t=[Qo.x,Qo.y,Qo.z],yc(t,za,Na,Ua,Zo))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,$r).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize($r).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(ri[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ri[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ri[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ri[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ri[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ri[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ri[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ri[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ri),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const ri=[new re,new re,new re,new re,new re,new re,new re,new re],$r=new re,Ko=new Mo,za=new re,Na=new re,Ua=new re,Ei=new re,Mi=new re,Xi=new re,ks=new re,Zo=new re,Qo=new re,Yi=new re;function yc(n,e,t,r,i){for(let a=0,s=n.length-3;a<=s;a+=3){Yi.fromArray(n,a);const o=i.x*Math.abs(Yi.x)+i.y*Math.abs(Yi.y)+i.z*Math.abs(Yi.z),l=e.dot(Yi),u=t.dot(Yi),c=r.dot(Yi);if(Math.max(-Math.max(l,u,c),Math.min(l,u,c))>o)return!1}return!0}const FP=new Mo,Os=new re,vc=new re;class ah{constructor(e=new re,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const r=this.center;t!==void 0?r.copy(t):FP.setFromPoints(e).getCenter(r);let i=0;for(let a=0,s=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Os.subVectors(e,this.center);const t=Os.lengthSq();if(t>this.radius*this.radius){const r=Math.sqrt(t),i=(r-this.radius)*.5;this.center.addScaledVector(Os,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(vc.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Os.copy(e.center).add(vc)),this.expandByPoint(Os.copy(e.center).sub(vc))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const ii=new re,wc=new re,Jo=new re,Ti=new re,bc=new re,el=new re,xc=new re;class kx{constructor(e=new re,t=new re(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ii)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const r=t.dot(this.direction);return r<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=ii.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ii.copy(this.origin).addScaledVector(this.direction,t),ii.distanceToSquared(e))}distanceSqToSegment(e,t,r,i){wc.copy(e).add(t).multiplyScalar(.5),Jo.copy(t).sub(e).normalize(),Ti.copy(this.origin).sub(wc);const a=e.distanceTo(t)*.5,s=-this.direction.dot(Jo),o=Ti.dot(this.direction),l=-Ti.dot(Jo),u=Ti.lengthSq(),c=Math.abs(1-s*s);let h,p,d,m;if(c>0)if(h=s*l-o,p=s*o-l,m=a*c,h>=0)if(p>=-m)if(p<=m){const y=1/c;h*=y,p*=y,d=h*(h+s*p+2*o)+p*(s*h+p+2*l)+u}else p=a,h=Math.max(0,-(s*p+o)),d=-h*h+p*(p+2*l)+u;else p=-a,h=Math.max(0,-(s*p+o)),d=-h*h+p*(p+2*l)+u;else p<=-m?(h=Math.max(0,-(-s*a+o)),p=h>0?-a:Math.min(Math.max(-a,-l),a),d=-h*h+p*(p+2*l)+u):p<=m?(h=0,p=Math.min(Math.max(-a,-l),a),d=p*(p+2*l)+u):(h=Math.max(0,-(s*a+o)),p=h>0?a:Math.min(Math.max(-a,-l),a),d=-h*h+p*(p+2*l)+u);else p=s>0?-a:a,h=Math.max(0,-(s*p+o)),d=-h*h+p*(p+2*l)+u;return r&&r.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(wc).addScaledVector(Jo,p),d}intersectSphere(e,t){ii.subVectors(e.center,this.origin);const r=ii.dot(this.direction),i=ii.dot(ii)-r*r,a=e.radius*e.radius;if(i>a)return null;const s=Math.sqrt(a-i),o=r-s,l=r+s;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/t;return r>=0?r:null}intersectPlane(e,t){const r=this.distanceToPlane(e);return r===null?null:this.at(r,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let r,i,a,s,o,l;const u=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,p=this.origin;return u>=0?(r=(e.min.x-p.x)*u,i=(e.max.x-p.x)*u):(r=(e.max.x-p.x)*u,i=(e.min.x-p.x)*u),c>=0?(a=(e.min.y-p.y)*c,s=(e.max.y-p.y)*c):(a=(e.max.y-p.y)*c,s=(e.min.y-p.y)*c),r>s||a>i||((a>r||isNaN(r))&&(r=a),(s=0?(o=(e.min.z-p.z)*h,l=(e.max.z-p.z)*h):(o=(e.max.z-p.z)*h,l=(e.min.z-p.z)*h),r>l||o>i)||((o>r||r!==r)&&(r=o),(l=0?r:i,t)}intersectsBox(e){return this.intersectBox(e,ii)!==null}intersectTriangle(e,t,r,i,a){bc.subVectors(t,e),el.subVectors(r,e),xc.crossVectors(bc,el);let s=this.direction.dot(xc),o;if(s>0){if(i)return null;o=1}else if(s<0)o=-1,s=-s;else return null;Ti.subVectors(this.origin,e);const l=o*this.direction.dot(el.crossVectors(Ti,el));if(l<0)return null;const u=o*this.direction.dot(bc.cross(Ti));if(u<0||l+u>s)return null;const c=-o*Ti.dot(xc);return c<0?null:this.at(c/s,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class In{constructor(e,t,r,i,a,s,o,l,u,c,h,p,d,m,y,g){In.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,r,i,a,s,o,l,u,c,h,p,d,m,y,g)}set(e,t,r,i,a,s,o,l,u,c,h,p,d,m,y,g){const _=this.elements;return _[0]=e,_[4]=t,_[8]=r,_[12]=i,_[1]=a,_[5]=s,_[9]=o,_[13]=l,_[2]=u,_[6]=c,_[10]=h,_[14]=p,_[3]=d,_[7]=m,_[11]=y,_[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new In().fromArray(this.elements)}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],t[9]=r[9],t[10]=r[10],t[11]=r[11],t[12]=r[12],t[13]=r[13],t[14]=r[14],t[15]=r[15],this}copyPosition(e){const t=this.elements,r=e.elements;return t[12]=r[12],t[13]=r[13],t[14]=r[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,r){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,t,r){return this.set(e.x,t.x,r.x,0,e.y,t.y,r.y,0,e.z,t.z,r.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,r=e.elements,i=1/Ba.setFromMatrixColumn(e,0).length(),a=1/Ba.setFromMatrixColumn(e,1).length(),s=1/Ba.setFromMatrixColumn(e,2).length();return t[0]=r[0]*i,t[1]=r[1]*i,t[2]=r[2]*i,t[3]=0,t[4]=r[4]*a,t[5]=r[5]*a,t[6]=r[6]*a,t[7]=0,t[8]=r[8]*s,t[9]=r[9]*s,t[10]=r[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,r=e.x,i=e.y,a=e.z,s=Math.cos(r),o=Math.sin(r),l=Math.cos(i),u=Math.sin(i),c=Math.cos(a),h=Math.sin(a);if(e.order==="XYZ"){const p=s*c,d=s*h,m=o*c,y=o*h;t[0]=l*c,t[4]=-l*h,t[8]=u,t[1]=d+m*u,t[5]=p-y*u,t[9]=-o*l,t[2]=y-p*u,t[6]=m+d*u,t[10]=s*l}else if(e.order==="YXZ"){const p=l*c,d=l*h,m=u*c,y=u*h;t[0]=p+y*o,t[4]=m*o-d,t[8]=s*u,t[1]=s*h,t[5]=s*c,t[9]=-o,t[2]=d*o-m,t[6]=y+p*o,t[10]=s*l}else if(e.order==="ZXY"){const p=l*c,d=l*h,m=u*c,y=u*h;t[0]=p-y*o,t[4]=-s*h,t[8]=m+d*o,t[1]=d+m*o,t[5]=s*c,t[9]=y-p*o,t[2]=-s*u,t[6]=o,t[10]=s*l}else if(e.order==="ZYX"){const p=s*c,d=s*h,m=o*c,y=o*h;t[0]=l*c,t[4]=m*u-d,t[8]=p*u+y,t[1]=l*h,t[5]=y*u+p,t[9]=d*u-m,t[2]=-u,t[6]=o*l,t[10]=s*l}else if(e.order==="YZX"){const p=s*l,d=s*u,m=o*l,y=o*u;t[0]=l*c,t[4]=y-p*h,t[8]=m*h+d,t[1]=h,t[5]=s*c,t[9]=-o*c,t[2]=-u*c,t[6]=d*h+m,t[10]=p-y*h}else if(e.order==="XZY"){const p=s*l,d=s*u,m=o*l,y=o*u;t[0]=l*c,t[4]=-h,t[8]=u*c,t[1]=p*h+y,t[5]=s*c,t[9]=d*h-m,t[2]=m*h-d,t[6]=o*c,t[10]=y*h+p}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(GP,e,WP)}lookAt(e,t,r){const i=this.elements;return sr.subVectors(e,t),sr.lengthSq()===0&&(sr.z=1),sr.normalize(),Ai.crossVectors(r,sr),Ai.lengthSq()===0&&(Math.abs(r.z)===1?sr.x+=1e-4:sr.z+=1e-4,sr.normalize(),Ai.crossVectors(r,sr)),Ai.normalize(),tl.crossVectors(sr,Ai),i[0]=Ai.x,i[4]=tl.x,i[8]=sr.x,i[1]=Ai.y,i[5]=tl.y,i[9]=sr.y,i[2]=Ai.z,i[6]=tl.z,i[10]=sr.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,a=this.elements,s=r[0],o=r[4],l=r[8],u=r[12],c=r[1],h=r[5],p=r[9],d=r[13],m=r[2],y=r[6],g=r[10],_=r[14],w=r[3],b=r[7],E=r[11],T=r[15],I=i[0],C=i[4],B=i[8],R=i[12],k=i[1],j=i[5],Q=i[9],ie=i[13],F=i[2],$=i[6],L=i[10],H=i[14],K=i[3],X=i[7],J=i[11],W=i[15];return a[0]=s*I+o*k+l*F+u*K,a[4]=s*C+o*j+l*$+u*X,a[8]=s*B+o*Q+l*L+u*J,a[12]=s*R+o*ie+l*H+u*W,a[1]=c*I+h*k+p*F+d*K,a[5]=c*C+h*j+p*$+d*X,a[9]=c*B+h*Q+p*L+d*J,a[13]=c*R+h*ie+p*H+d*W,a[2]=m*I+y*k+g*F+_*K,a[6]=m*C+y*j+g*$+_*X,a[10]=m*B+y*Q+g*L+_*J,a[14]=m*R+y*ie+g*H+_*W,a[3]=w*I+b*k+E*F+T*K,a[7]=w*C+b*j+E*$+T*X,a[11]=w*B+b*Q+E*L+T*J,a[15]=w*R+b*ie+E*H+T*W,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[4],i=e[8],a=e[12],s=e[1],o=e[5],l=e[9],u=e[13],c=e[2],h=e[6],p=e[10],d=e[14],m=e[3],y=e[7],g=e[11],_=e[15];return m*(+a*l*h-i*u*h-a*o*p+r*u*p+i*o*d-r*l*d)+y*(+t*l*d-t*u*p+a*s*p-i*s*d+i*u*c-a*l*c)+g*(+t*u*h-t*o*d-a*s*h+r*s*d+a*o*c-r*u*c)+_*(-i*o*c-t*l*h+t*o*p+i*s*h-r*s*p+r*l*c)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=r),this}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],d=e[11],m=e[12],y=e[13],g=e[14],_=e[15],w=h*g*u-y*p*u+y*l*d-o*g*d-h*l*_+o*p*_,b=m*p*u-c*g*u-m*l*d+s*g*d+c*l*_-s*p*_,E=c*y*u-m*h*u+m*o*d-s*y*d-c*o*_+s*h*_,T=m*h*l-c*y*l-m*o*p+s*y*p+c*o*g-s*h*g,I=t*w+r*b+i*E+a*T;if(I===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/I;return e[0]=w*C,e[1]=(y*p*a-h*g*a-y*i*d+r*g*d+h*i*_-r*p*_)*C,e[2]=(o*g*a-y*l*a+y*i*u-r*g*u-o*i*_+r*l*_)*C,e[3]=(h*l*a-o*p*a-h*i*u+r*p*u+o*i*d-r*l*d)*C,e[4]=b*C,e[5]=(c*g*a-m*p*a+m*i*d-t*g*d-c*i*_+t*p*_)*C,e[6]=(m*l*a-s*g*a-m*i*u+t*g*u+s*i*_-t*l*_)*C,e[7]=(s*p*a-c*l*a+c*i*u-t*p*u-s*i*d+t*l*d)*C,e[8]=E*C,e[9]=(m*h*a-c*y*a-m*r*d+t*y*d+c*r*_-t*h*_)*C,e[10]=(s*y*a-m*o*a+m*r*u-t*y*u-s*r*_+t*o*_)*C,e[11]=(c*o*a-s*h*a-c*r*u+t*h*u+s*r*d-t*o*d)*C,e[12]=T*C,e[13]=(c*y*i-m*h*i+m*r*p-t*y*p-c*r*g+t*h*g)*C,e[14]=(m*o*i-s*y*i-m*r*l+t*y*l+s*r*g-t*o*g)*C,e[15]=(s*h*i-c*o*i+c*r*l-t*h*l-s*r*p+t*o*p)*C,this}scale(e){const t=this.elements,r=e.x,i=e.y,a=e.z;return t[0]*=r,t[4]*=i,t[8]*=a,t[1]*=r,t[5]*=i,t[9]*=a,t[2]*=r,t[6]*=i,t[10]*=a,t[3]*=r,t[7]*=i,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,r,i))}makeTranslation(e,t,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,r,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,t,-r,0,0,r,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,0,r,0,0,1,0,0,-r,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,-r,0,0,r,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const r=Math.cos(t),i=Math.sin(t),a=1-r,s=e.x,o=e.y,l=e.z,u=a*s,c=a*o;return this.set(u*s+r,u*o-i*l,u*l+i*o,0,u*o+i*l,c*o+r,c*l-i*s,0,u*l-i*o,c*l+i*s,a*l*l+r,0,0,0,0,1),this}makeScale(e,t,r){return this.set(e,0,0,0,0,t,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,t,r,i,a,s){return this.set(1,r,a,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,r){const i=this.elements,a=t._x,s=t._y,o=t._z,l=t._w,u=a+a,c=s+s,h=o+o,p=a*u,d=a*c,m=a*h,y=s*c,g=s*h,_=o*h,w=l*u,b=l*c,E=l*h,T=r.x,I=r.y,C=r.z;return i[0]=(1-(y+_))*T,i[1]=(d+E)*T,i[2]=(m-b)*T,i[3]=0,i[4]=(d-E)*I,i[5]=(1-(p+_))*I,i[6]=(g+w)*I,i[7]=0,i[8]=(m+b)*C,i[9]=(g-w)*C,i[10]=(1-(p+y))*C,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,r){const i=this.elements;let a=Ba.set(i[0],i[1],i[2]).length();const s=Ba.set(i[4],i[5],i[6]).length(),o=Ba.set(i[8],i[9],i[10]).length();this.determinant()<0&&(a=-a),e.x=i[12],e.y=i[13],e.z=i[14],Rr.copy(this);const u=1/a,c=1/s,h=1/o;return Rr.elements[0]*=u,Rr.elements[1]*=u,Rr.elements[2]*=u,Rr.elements[4]*=c,Rr.elements[5]*=c,Rr.elements[6]*=c,Rr.elements[8]*=h,Rr.elements[9]*=h,Rr.elements[10]*=h,t.setFromRotationMatrix(Rr),r.x=a,r.y=s,r.z=o,this}makePerspective(e,t,r,i,a,s,o=di){const l=this.elements,u=2*a/(t-e),c=2*a/(r-i),h=(t+e)/(t-e),p=(r+i)/(r-i);let d,m;if(o===di)d=-(s+a)/(s-a),m=-2*s*a/(s-a);else if(o===Kl)d=-s/(s-a),m=-s*a/(s-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=u,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=c,l[9]=p,l[13]=0,l[2]=0,l[6]=0,l[10]=d,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,r,i,a,s,o=di){const l=this.elements,u=1/(t-e),c=1/(r-i),h=1/(s-a),p=(t+e)*u,d=(r+i)*c;let m,y;if(o===di)m=(s+a)*h,y=-2*h;else if(o===Kl)m=a*h,y=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*u,l[4]=0,l[8]=0,l[12]=-p,l[1]=0,l[5]=2*c,l[9]=0,l[13]=-d,l[2]=0,l[6]=0,l[10]=y,l[14]=-m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,r=e.elements;for(let i=0;i<16;i++)if(t[i]!==r[i])return!1;return!0}fromArray(e,t=0){for(let r=0;r<16;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e[t+9]=r[9],e[t+10]=r[10],e[t+11]=r[11],e[t+12]=r[12],e[t+13]=r[13],e[t+14]=r[14],e[t+15]=r[15],e}}const Ba=new re,Rr=new In,GP=new re(0,0,0),WP=new re(1,1,1),Ai=new re,tl=new re,sr=new re,Qg=new In,Jg=new ya;class fu{constructor(e=0,t=0,r=0,i=fu.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,r,i=this._order){return this._x=e,this._y=t,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,r=!0){const i=e.elements,a=i[0],s=i[4],o=i[8],l=i[1],u=i[5],c=i[9],h=i[2],p=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Ln(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,a)):(this._x=Math.atan2(p,u),this._z=0);break;case"YXZ":this._x=Math.asin(-Ln(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(l,u)):(this._y=Math.atan2(-h,a),this._z=0);break;case"ZXY":this._x=Math.asin(Ln(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,u)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-Ln(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(p,d),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-s,u));break;case"YZX":this._z=Math.asin(Ln(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-c,u),this._y=Math.atan2(-h,a)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-Ln(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(p,u),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,r){return Qg.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Qg,t,r)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Jg.setFromEuler(this),this.setFromQuaternion(Jg,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}fu.DEFAULT_ORDER="XYZ";class Ox{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let r=0;r0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let u=0,c=l.length;u0){i.children=[];for(let o=0;o0){i.animations=[];for(let o=0;o0&&(r.geometries=o),l.length>0&&(r.materials=l),u.length>0&&(r.textures=u),c.length>0&&(r.images=c),h.length>0&&(r.shapes=h),p.length>0&&(r.skeletons=p),d.length>0&&(r.animations=d),m.length>0&&(r.nodes=m)}return r.object=i,r;function s(o){const l=[];for(const u in o){const c=o[u];delete c.metadata,l.push(c)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let r=0;r0?i.multiplyScalar(1/Math.sqrt(a)):i.set(0,0,0)}static getBarycoord(e,t,r,i,a){Ir.subVectors(i,t),si.subVectors(r,t),Sc.subVectors(e,t);const s=Ir.dot(Ir),o=Ir.dot(si),l=Ir.dot(Sc),u=si.dot(si),c=si.dot(Sc),h=s*u-o*o;if(h===0)return a.set(0,0,0),null;const p=1/h,d=(u*l-o*c)*p,m=(s*c-o*l)*p;return a.set(1-d-m,m,d)}static containsPoint(e,t,r,i){return this.getBarycoord(e,t,r,i,oi)===null?!1:oi.x>=0&&oi.y>=0&&oi.x+oi.y<=1}static getUV(e,t,r,i,a,s,o,l){return rl===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),rl=!0),this.getInterpolation(e,t,r,i,a,s,o,l)}static getInterpolation(e,t,r,i,a,s,o,l){return this.getBarycoord(e,t,r,i,oi)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,oi.x),l.addScaledVector(s,oi.y),l.addScaledVector(o,oi.z),l)}static isFrontFacing(e,t,r,i){return Ir.subVectors(r,t),si.subVectors(e,t),Ir.cross(si).dot(i)<0}set(e,t,r){return this.a.copy(e),this.b.copy(t),this.c.copy(r),this}setFromPointsAndIndices(e,t,r,i){return this.a.copy(e[t]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,r,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ir.subVectors(this.c,this.b),si.subVectors(this.a,this.b),Ir.cross(si).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Or.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Or.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,r,i,a){return rl===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),rl=!0),Or.getInterpolation(e,this.a,this.b,this.c,t,r,i,a)}getInterpolation(e,t,r,i,a){return Or.getInterpolation(e,this.a,this.b,this.c,t,r,i,a)}containsPoint(e){return Or.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Or.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const r=this.a,i=this.b,a=this.c;let s,o;Ga.subVectors(i,r),Wa.subVectors(a,r),Ec.subVectors(e,r);const l=Ga.dot(Ec),u=Wa.dot(Ec);if(l<=0&&u<=0)return t.copy(r);Mc.subVectors(e,i);const c=Ga.dot(Mc),h=Wa.dot(Mc);if(c>=0&&h<=c)return t.copy(i);const p=l*h-c*u;if(p<=0&&l>=0&&c<=0)return s=l/(l-c),t.copy(r).addScaledVector(Ga,s);Tc.subVectors(e,a);const d=Ga.dot(Tc),m=Wa.dot(Tc);if(m>=0&&d<=m)return t.copy(a);const y=d*u-l*m;if(y<=0&&u>=0&&m<=0)return o=u/(u-m),t.copy(r).addScaledVector(Wa,o);const g=c*m-d*h;if(g<=0&&h-c>=0&&d-m>=0)return i_.subVectors(a,i),o=(h-c)/(h-c+(d-m)),t.copy(i).addScaledVector(i_,o);const _=1/(g+y+p);return s=y*_,o=p*_,t.copy(r).addScaledVector(Ga,s).addScaledVector(Wa,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Dx={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ci={h:0,s:0,l:0},il={h:0,s:0,l:0};function Ac(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class qt{constructor(e,t,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,r)}set(e,t,r){if(t===void 0&&r===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=En){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Qt.toWorkingColorSpace(this,t),this}setRGB(e,t,r,i=Qt.workingColorSpace){return this.r=e,this.g=t,this.b=r,Qt.toWorkingColorSpace(this,i),this}setHSL(e,t,r,i=Qt.workingColorSpace){if(e=ih(e,1),t=Ln(t,0,1),r=Ln(r,0,1),t===0)this.r=this.g=this.b=r;else{const a=r<=.5?r*(1+t):r+t-r*t,s=2*r-a;this.r=Ac(s,a,e+1/3),this.g=Ac(s,a,e),this.b=Ac(s,a,e-1/3)}return Qt.toWorkingColorSpace(this,i),this}setStyle(e,t=En){function r(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const s=i[1],o=i[2];switch(s){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return r(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return r(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return r(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=i[1],s=a.length;if(s===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(s===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=En){const r=Dx[e.toLowerCase()];return r!==void 0?this.setHex(r,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=as(e.r),this.g=as(e.g),this.b=as(e.b),this}copyLinearToSRGB(e){return this.r=mc(e.r),this.g=mc(e.g),this.b=mc(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=En){return Qt.fromWorkingColorSpace(Dn.copy(this),e),Math.round(Ln(Dn.r*255,0,255))*65536+Math.round(Ln(Dn.g*255,0,255))*256+Math.round(Ln(Dn.b*255,0,255))}getHexString(e=En){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Qt.workingColorSpace){Qt.fromWorkingColorSpace(Dn.copy(this),t);const r=Dn.r,i=Dn.g,a=Dn.b,s=Math.max(r,i,a),o=Math.min(r,i,a);let l,u;const c=(o+s)/2;if(o===s)l=0,u=0;else{const h=s-o;switch(u=c<=.5?h/(s+o):h/(2-s-o),s){case r:l=(i-a)/h+(i0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const r=e[t];if(r===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[t]=r}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==is&&(r.blending=this.blending),this.side!==Ui&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==td&&(r.blendSrc=this.blendSrc),this.blendDst!==nd&&(r.blendDst=this.blendDst),this.blendEquation!==ra&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==ql&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Vg&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Da&&(r.stencilFail=this.stencilFail),this.stencilZFail!==Da&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==Da&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(a){const s=[];for(const o in a){const l=a[o];delete l.metadata,s.push(l)}return s}if(t){const a=i(e.textures),s=i(e.images);a.length>0&&(r.textures=a),s.length>0&&(r.images=s)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let r=null;if(t!==null){const i=t.length;r=new Array(i);for(let a=0;a!==i;++a)r[a]=t[a].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Lx extends To{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new qt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=_x,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const _n=new re,al=new kt;class Yr{constructor(e,t,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=r,this.usage=Hg,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=ki,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,r){e*=this.itemSize,r*=t.itemSize;for(let i=0,a=this.itemSize;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const u in l)l[u]!==void 0&&(e[u]=l[u]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const r=this.attributes;for(const l in r){const u=r[l];e.data.attributes[l]=u.toJSON(e.data)}const i={};let a=!1;for(const l in this.morphAttributes){const u=this.morphAttributes[l],c=[];for(let h=0,p=u.length;h0&&(i[l]=c,a=!0)}a&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone(t));const i=e.attributes;for(const u in i){const c=i[u];this.setAttribute(u,c.clone(t))}const a=e.morphAttributes;for(const u in a){const c=[],h=a[u];for(let p=0,d=h.length;p0){const i=t[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,s=i.length;a(e.far-e.near)**2))&&(a_.copy(a).invert(),Ki.copy(e.ray).applyMatrix4(a_),!(r.boundingBox!==null&&Ki.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,t,Ki)))}_computeIntersections(e,t,r){let i;const a=this.geometry,s=this.material,o=a.index,l=a.attributes.position,u=a.attributes.uv,c=a.attributes.uv1,h=a.attributes.normal,p=a.groups,d=a.drawRange;if(o!==null)if(Array.isArray(s))for(let m=0,y=p.length;mt.far?null:{distance:u,point:hl.clone(),object:n}}function pl(n,e,t,r,i,a,s,o,l,u){n.getVertexPosition(o,Ha),n.getVertexPosition(l,qa),n.getVertexPosition(u,ja);const c=ZP(n,e,t,r,Ha,qa,ja,dl);if(c){i&&(ll.fromBufferAttribute(i,o),ul.fromBufferAttribute(i,l),cl.fromBufferAttribute(i,u),c.uv=Or.getInterpolation(dl,Ha,qa,ja,ll,ul,cl,new kt)),a&&(ll.fromBufferAttribute(a,o),ul.fromBufferAttribute(a,l),cl.fromBufferAttribute(a,u),c.uv1=Or.getInterpolation(dl,Ha,qa,ja,ll,ul,cl,new kt),c.uv2=c.uv1),s&&(o_.fromBufferAttribute(s,o),l_.fromBufferAttribute(s,l),u_.fromBufferAttribute(s,u),c.normal=Or.getInterpolation(dl,Ha,qa,ja,o_,l_,u_,new re),c.normal.dot(r.direction)>0&&c.normal.multiplyScalar(-1));const h={a:o,b:l,c:u,normal:new re,materialIndex:0};Or.getNormal(Ha,qa,ja,h.normal),c.face=h}return c}class Ao extends Ma{constructor(e=1,t=1,r=1,i=1,a=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:r,widthSegments:i,heightSegments:a,depthSegments:s};const o=this;i=Math.floor(i),a=Math.floor(a),s=Math.floor(s);const l=[],u=[],c=[],h=[];let p=0,d=0;m("z","y","x",-1,-1,r,t,e,s,a,0),m("z","y","x",1,-1,r,t,-e,s,a,1),m("x","z","y",1,1,e,r,t,i,s,2),m("x","z","y",1,-1,e,r,-t,i,s,3),m("x","y","z",1,-1,e,t,r,i,a,4),m("x","y","z",-1,-1,e,t,-r,i,a,5),this.setIndex(l),this.setAttribute("position",new ha(u,3)),this.setAttribute("normal",new ha(c,3)),this.setAttribute("uv",new ha(h,2));function m(y,g,_,w,b,E,T,I,C,B,R){const k=E/C,j=T/B,Q=E/2,ie=T/2,F=I/2,$=C+1,L=B+1;let H=0,K=0;const X=new re;for(let J=0;J0?1:-1,c.push(X.x,X.y,X.z),h.push(ae/C),h.push(1-J/B),H+=1}}for(let J=0;J0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const r={};for(const i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(t.extensions=r),t}}class Bx extends ir{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new In,this.projectionMatrix=new In,this.projectionMatrixInverse=new In,this.coordinateSystem=di}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}class gr extends Bx{constructor(e=50,t=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=ro*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Vs*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ro*2*Math.atan(Math.tan(Vs*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,t,r,i,a,s){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=a,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Vs*.5*this.fov)/this.zoom,r=2*t,i=this.aspect*r,a=-.5*i;const s=this.view;if(this.view!==null&&this.view.enabled){const l=s.fullWidth,u=s.fullHeight;a+=s.offsetX*i/l,t-=s.offsetY*r/u,i*=s.width/l,r*=s.height/u}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+i,t,t-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Xa=-90,Ya=1;class nk extends ir{constructor(e,t,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new gr(Xa,Ya,e,t);i.layers=this.layers,this.add(i);const a=new gr(Xa,Ya,e,t);a.layers=this.layers,this.add(a);const s=new gr(Xa,Ya,e,t);s.layers=this.layers,this.add(s);const o=new gr(Xa,Ya,e,t);o.layers=this.layers,this.add(o);const l=new gr(Xa,Ya,e,t);l.layers=this.layers,this.add(l);const u=new gr(Xa,Ya,e,t);u.layers=this.layers,this.add(u)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[r,i,a,s,o,l]=t;for(const u of t)this.remove(u);if(e===di)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Kl)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const u of t)this.add(u),u.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,s,o,l,u,c]=this.children,h=e.getRenderTarget(),p=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;const y=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(t,a),e.setRenderTarget(r,1,i),e.render(t,s),e.setRenderTarget(r,2,i),e.render(t,o),e.setRenderTarget(r,3,i),e.render(t,l),e.setRenderTarget(r,4,i),e.render(t,u),r.texture.generateMipmaps=y,e.setRenderTarget(r,5,i),e.render(t,c),e.setRenderTarget(h,p,d),e.xr.enabled=m,r.texture.needsPMREMUpdate=!0}}class Fx extends Xn{constructor(e,t,r,i,a,s,o,l,u,c){e=e!==void 0?e:[],t=t!==void 0?t:cs,super(e,t,r,i,a,s,o,l,u,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class rk extends _a{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];t.encoding!==void 0&&(qs("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),t.colorSpace=t.encoding===da?En:_r),this.texture=new Fx(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:mr}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},i=new Ao(5,5,5),a=new va({name:"CubemapFromEquirect",uniforms:ps(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:rr,blending:Oi});a.uniforms.tEquirect.value=t;const s=new hi(i,a),o=t.minFilter;return t.minFilter===to&&(t.minFilter=mr),new nk(1,10,this).update(e,s),t.minFilter=o,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,r,i){const a=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,r,i);e.setRenderTarget(a)}}const Rc=new re,ik=new re,ak=new Lt;class Ri{constructor(e=new re(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,r,i){return this.normal.set(e,t,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,r){const i=Rc.subVectors(r,t).cross(ik.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const r=e.delta(Rc),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const a=-(e.start.dot(this.normal)+this.constant)/i;return a<0||a>1?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return t<0&&r>0||r<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const r=t||ak.getNormalMatrix(e),i=this.coplanarPoint(Rc).applyMatrix4(e),a=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Zi=new ah,fl=new re;class Gx{constructor(e=new Ri,t=new Ri,r=new Ri,i=new Ri,a=new Ri,s=new Ri){this.planes=[e,t,r,i,a,s]}set(e,t,r,i,a,s){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(r),o[3].copy(i),o[4].copy(a),o[5].copy(s),this}copy(e){const t=this.planes;for(let r=0;r<6;r++)t[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,t=di){const r=this.planes,i=e.elements,a=i[0],s=i[1],o=i[2],l=i[3],u=i[4],c=i[5],h=i[6],p=i[7],d=i[8],m=i[9],y=i[10],g=i[11],_=i[12],w=i[13],b=i[14],E=i[15];if(r[0].setComponents(l-a,p-u,g-d,E-_).normalize(),r[1].setComponents(l+a,p+u,g+d,E+_).normalize(),r[2].setComponents(l+s,p+c,g+m,E+w).normalize(),r[3].setComponents(l-s,p-c,g-m,E-w).normalize(),r[4].setComponents(l-o,p-h,g-y,E-b).normalize(),t===di)r[5].setComponents(l+o,p+h,g+y,E+b).normalize();else if(t===Kl)r[5].setComponents(o,h,y,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Zi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Zi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Zi)}intersectsSprite(e){return Zi.center.set(0,0,0),Zi.radius=.7071067811865476,Zi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Zi)}intersectsSphere(e){const t=this.planes,r=e.center,i=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(r)0?e.max.x:e.min.x,fl.y=i.normal.y>0?e.max.y:e.min.y,fl.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(fl)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let r=0;r<6;r++)if(t[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function Wx(){let n=null,e=!1,t=null,r=null;function i(a,s){t(a,s),r=n.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(r=n.requestAnimationFrame(i),e=!0)},stop:function(){n.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function sk(n,e){const t=e.isWebGL2,r=new WeakMap;function i(u,c){const h=u.array,p=u.usage,d=h.byteLength,m=n.createBuffer();n.bindBuffer(c,m),n.bufferData(c,h,p),u.onUploadCallback();let y;if(h instanceof Float32Array)y=n.FLOAT;else if(h instanceof Uint16Array)if(u.isFloat16BufferAttribute)if(t)y=n.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else y=n.UNSIGNED_SHORT;else if(h instanceof Int16Array)y=n.SHORT;else if(h instanceof Uint32Array)y=n.UNSIGNED_INT;else if(h instanceof Int32Array)y=n.INT;else if(h instanceof Int8Array)y=n.BYTE;else if(h instanceof Uint8Array)y=n.UNSIGNED_BYTE;else if(h instanceof Uint8ClampedArray)y=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+h);return{buffer:m,type:y,bytesPerElement:h.BYTES_PER_ELEMENT,version:u.version,size:d}}function a(u,c,h){const p=c.array,d=c._updateRange,m=c.updateRanges;if(n.bindBuffer(h,u),d.count===-1&&m.length===0&&n.bufferSubData(h,0,p),m.length!==0){for(let y=0,g=m.length;y 0 vec4 plane; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif`,Sk=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,Ek=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,Mk=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,Tk=`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; #endif`,Ak=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; #endif`,Ck=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) varying vec3 vColor; #endif`,$k=`#if defined( USE_COLOR_ALPHA ) vColor = vec4( 1.0 ); #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) vColor = vec3( 1.0 ); #endif #ifdef USE_COLOR vColor *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.xyz *= instanceColor.xyz; #endif`,Rk=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } mat3 transposeMat3( const in mat3 m ) { mat3 tmp; tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); return tmp; } float luminance( const in vec3 rgb ) { const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 ); return dot( weights, rgb ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,Ik=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,Pk=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`,kk=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,Ok=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,Dk=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); totalEmissiveRadiance *= emissiveColor.rgb; #endif`,Lk=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,zk="gl_FragColor = linearToOutputTexel( gl_FragColor );",Nk=` const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3( vec3( 0.8224621, 0.177538, 0.0 ), vec3( 0.0331941, 0.9668058, 0.0 ), vec3( 0.0170827, 0.0723974, 0.9105199 ) ); const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3( vec3( 1.2249401, - 0.2249404, 0.0 ), vec3( - 0.0420569, 1.0420571, 0.0 ), vec3( - 0.0196376, - 0.0786361, 1.0982735 ) ); vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) { return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a ); } vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) { return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a ); } vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); } vec4 LinearToLinear( in vec4 value ) { return value; } vec4 LinearTosRGB( in vec4 value ) { return sRGBTransferOETF( value ); }`,Uk=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); #else vec4 envColor = vec4( 0.0 ); #endif #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif`,Bk=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,Fk=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,Gk=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,Wk=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,Vk=`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,Hk=`#ifdef USE_FOG varying float vFogDepth; #endif`,qk=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,jk=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,Xk=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,Yk=`#ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; reflectedLight.indirectDiffuse += lightMapIrradiance; #endif`,Kk=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,Zk=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,Qk=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Jk=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { #if defined ( LEGACY_LIGHTS ) if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) { return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent ); } return 1.0; #else float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; #endif } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif`,eO=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,tO=`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,nO=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,rO=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,iO=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,aO=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`,sO=`struct PhysicalMaterial { vec3 diffuseColor; float roughness; vec3 specularColor; float specularF90; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); float v = 0.5 / ( gv + gl ); return saturate(v); } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColor; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); return saturate( DG * RECIPROCAL_PI ); } vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); vec4 r = roughness * c0 + c1; float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; return fab; } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { vec2 fab = DFGApprox( normal, viewDir, roughness ); return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif vec2 fab = DFGApprox( normal, viewDir, roughness ); #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); #endif reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); #endif vec3 singleScattering = vec3( 0.0 ); vec3 multiScattering = vec3( 0.0 ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); #endif vec3 totalScattering = singleScattering + multiScattering; vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); reflectedLight.indirectSpecular += radiance * singleScattering; reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,oO=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,lO=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`,uO=`#if defined( RE_IndirectDiffuse ) RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`,cO=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,dO=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,hO=`#ifdef USE_LOGDEPTHBUF #ifdef USE_LOGDEPTHBUF_EXT varying float vFragDepth; varying float vIsPerspective; #else uniform float logDepthBufFC; #endif #endif`,pO=`#ifdef USE_LOGDEPTHBUF #ifdef USE_LOGDEPTHBUF_EXT vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #else if ( isPerspectiveMatrix( projectionMatrix ) ) { gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0; gl_Position.z *= gl_Position.w; } #endif #endif`,fO=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); #endif diffuseColor *= sampledDiffuseColor; #endif`,mO=`#ifdef USE_MAP uniform sampler2D map; #endif`,gO=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,_O=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,yO=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,vO=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,wO=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,bO=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; #ifdef MORPHTARGETS_TEXTURE for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #else objectNormal += morphNormal0 * morphTargetInfluences[ 0 ]; objectNormal += morphNormal1 * morphTargetInfluences[ 1 ]; objectNormal += morphNormal2 * morphTargetInfluences[ 2 ]; objectNormal += morphNormal3 * morphTargetInfluences[ 3 ]; #endif #endif`,xO=`#ifdef USE_MORPHTARGETS uniform float morphTargetBaseInfluence; #ifdef MORPHTARGETS_TEXTURE uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #else #ifndef USE_MORPHNORMALS uniform float morphTargetInfluences[ 8 ]; #else uniform float morphTargetInfluences[ 4 ]; #endif #endif #endif`,SO=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; #ifdef MORPHTARGETS_TEXTURE for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #else transformed += morphTarget0 * morphTargetInfluences[ 0 ]; transformed += morphTarget1 * morphTargetInfluences[ 1 ]; transformed += morphTarget2 * morphTargetInfluences[ 2 ]; transformed += morphTarget3 * morphTargetInfluences[ 3 ]; #ifndef USE_MORPHNORMALS transformed += morphTarget4 * morphTargetInfluences[ 4 ]; transformed += morphTarget5 * morphTargetInfluences[ 5 ]; transformed += morphTarget6 * morphTargetInfluences[ 6 ]; transformed += morphTarget7 * morphTargetInfluences[ 7 ]; #endif #endif #endif`,EO=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`,MO=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,TO=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,AO=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,CO=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,$O=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,RO=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,IO=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,PO=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,kO=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,OO=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,DO=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.; const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); const float ShiftRight8 = 1. / 256.; vec4 packDepthToRGBA( const in float v ) { vec4 r = vec4( fract( v * PackFactors ), v ); r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale; } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors ); } vec2 packDepthToRG( in highp float v ) { return packDepthToRGBA( v ).yx; } float unpackRGToDepth( const in highp vec2 v ) { return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) ); } vec4 pack2HalfToRGBA( vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { return depth * ( near - far ) - near; } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { return ( near * far ) / ( ( far - near ) * depth - far ); }`,LO=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,zO=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,NO=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,UO=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,BO=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,FO=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,GO=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; struct SpotLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); } vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { return unpackRGBATo2Half( texture2D( shadow, uv ) ); } float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ float occlusion = 1.0; vec2 distribution = texture2DDistribution( shadow, uv ); float hard_shadow = step( compare , distribution.x ); if (hard_shadow != 1.0 ) { float distance = compare - distribution.x ; float variance = max( 0.00000, distribution.y * distribution.y ); float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); } return occlusion; } float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { #if defined( SHADOWMAP_TYPE_PCF ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx0 = - texelSize.x * shadowRadius; float dy0 = - texelSize.y * shadowRadius; float dx1 = + texelSize.x * shadowRadius; float dy1 = + texelSize.y * shadowRadius; float dx2 = dx0 / 2.0; float dy2 = dy0 / 2.0; float dx3 = dx1 / 2.0; float dy3 = dy1 / 2.0; shadow = ( texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) ) * ( 1.0 / 17.0 ); #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx = texelSize.x; float dy = texelSize.y; vec2 uv = shadowCoord.xy; vec2 f = fract( uv * shadowMapSize + 0.5 ); uv -= f * texelSize; shadow = ( texture2DCompare( shadowMap, uv, shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), f.x ), mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), f.x ), f.y ) ) * ( 1.0 / 9.0 ); #elif defined( SHADOWMAP_TYPE_VSM ) shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); #else shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); #endif } return shadow; } vec2 cubeToUV( vec3 v, float texelSizeY ) { vec3 absV = abs( v ); float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); absV *= scaleToCube; v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); vec2 planar = v.xy; float almostATexel = 1.5 * texelSizeY; float almostOne = 1.0 - almostATexel; if ( absV.z >= almostOne ) { if ( v.z > 0.0 ) planar.x = 4.0 - v.x; } else if ( absV.x >= almostOne ) { float signX = sign( v.x ); planar.x = v.z * signX + 2.0 * signX; } else if ( absV.y >= almostOne ) { float signY = sign( v.y ); planar.x = v.x + 2.0 * signY + 2.0; planar.y = v.z * signY - 2.0; } return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); } float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); vec3 lightToPosition = shadowCoord.xyz; float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; return ( texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) ) * ( 1.0 / 9.0 ); #else return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); #endif } #endif`,WO=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,VO=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,HO=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,qO=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,jO=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`,XO=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,YO=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,KO=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,ZO=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,QO=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,JO=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 OptimizedCineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color *= toneMappingExposure; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; return color; } vec3 CustomToneMapping( vec3 color ) { return color; }`,eD=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,tD=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,nD=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,rD=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,iD=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,aD=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`;const sD=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,oD=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,lD=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,uD=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float flipEnvMap; uniform float backgroundBlurriness; uniform float backgroundIntensity; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,cD=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,dD=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,hD=`#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,pD=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include vec4 diffuseColor = vec4( 1.0 ); #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #endif }`,fD=`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,mD=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include #include void main () { #include vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = packDepthToRGBA( dist ); }`,gD=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,_D=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,yD=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include }`,vD=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,wD=`#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,bD=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,xD=`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,SD=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,ED=`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,MD=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,TD=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,AD=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include void main() { #include #include #include #include gl_FragColor = vec4( packNormalToRGB( normal ), opacity ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,CD=`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,$D=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,RD=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,ID=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`,PD=`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,kD=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,OD=`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,DD=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { #include vec3 outgoingLight = vec3( 0.0 ); vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,LD=`#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`,zD=`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include }`,ND=`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); vec2 scale; scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,UD=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { #include vec3 outgoingLight = vec3( 0.0 ); vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`,Pt={alphahash_fragment:ok,alphahash_pars_fragment:lk,alphamap_fragment:uk,alphamap_pars_fragment:ck,alphatest_fragment:dk,alphatest_pars_fragment:hk,aomap_fragment:pk,aomap_pars_fragment:fk,batching_pars_vertex:mk,batching_vertex:gk,begin_vertex:_k,beginnormal_vertex:yk,bsdfs:vk,iridescence_fragment:wk,bumpmap_pars_fragment:bk,clipping_planes_fragment:xk,clipping_planes_pars_fragment:Sk,clipping_planes_pars_vertex:Ek,clipping_planes_vertex:Mk,color_fragment:Tk,color_pars_fragment:Ak,color_pars_vertex:Ck,color_vertex:$k,common:Rk,cube_uv_reflection_fragment:Ik,defaultnormal_vertex:Pk,displacementmap_pars_vertex:kk,displacementmap_vertex:Ok,emissivemap_fragment:Dk,emissivemap_pars_fragment:Lk,colorspace_fragment:zk,colorspace_pars_fragment:Nk,envmap_fragment:Uk,envmap_common_pars_fragment:Bk,envmap_pars_fragment:Fk,envmap_pars_vertex:Gk,envmap_physical_pars_fragment:eO,envmap_vertex:Wk,fog_vertex:Vk,fog_pars_vertex:Hk,fog_fragment:qk,fog_pars_fragment:jk,gradientmap_pars_fragment:Xk,lightmap_fragment:Yk,lightmap_pars_fragment:Kk,lights_lambert_fragment:Zk,lights_lambert_pars_fragment:Qk,lights_pars_begin:Jk,lights_toon_fragment:tO,lights_toon_pars_fragment:nO,lights_phong_fragment:rO,lights_phong_pars_fragment:iO,lights_physical_fragment:aO,lights_physical_pars_fragment:sO,lights_fragment_begin:oO,lights_fragment_maps:lO,lights_fragment_end:uO,logdepthbuf_fragment:cO,logdepthbuf_pars_fragment:dO,logdepthbuf_pars_vertex:hO,logdepthbuf_vertex:pO,map_fragment:fO,map_pars_fragment:mO,map_particle_fragment:gO,map_particle_pars_fragment:_O,metalnessmap_fragment:yO,metalnessmap_pars_fragment:vO,morphcolor_vertex:wO,morphnormal_vertex:bO,morphtarget_pars_vertex:xO,morphtarget_vertex:SO,normal_fragment_begin:EO,normal_fragment_maps:MO,normal_pars_fragment:TO,normal_pars_vertex:AO,normal_vertex:CO,normalmap_pars_fragment:$O,clearcoat_normal_fragment_begin:RO,clearcoat_normal_fragment_maps:IO,clearcoat_pars_fragment:PO,iridescence_pars_fragment:kO,opaque_fragment:OO,packing:DO,premultiplied_alpha_fragment:LO,project_vertex:zO,dithering_fragment:NO,dithering_pars_fragment:UO,roughnessmap_fragment:BO,roughnessmap_pars_fragment:FO,shadowmap_pars_fragment:GO,shadowmap_pars_vertex:WO,shadowmap_vertex:VO,shadowmask_pars_fragment:HO,skinbase_vertex:qO,skinning_pars_vertex:jO,skinning_vertex:XO,skinnormal_vertex:YO,specularmap_fragment:KO,specularmap_pars_fragment:ZO,tonemapping_fragment:QO,tonemapping_pars_fragment:JO,transmission_fragment:eD,transmission_pars_fragment:tD,uv_pars_fragment:nD,uv_pars_vertex:rD,uv_vertex:iD,worldpos_vertex:aD,background_vert:sD,background_frag:oD,backgroundCube_vert:lD,backgroundCube_frag:uD,cube_vert:cD,cube_frag:dD,depth_vert:hD,depth_frag:pD,distanceRGBA_vert:fD,distanceRGBA_frag:mD,equirect_vert:gD,equirect_frag:_D,linedashed_vert:yD,linedashed_frag:vD,meshbasic_vert:wD,meshbasic_frag:bD,meshlambert_vert:xD,meshlambert_frag:SD,meshmatcap_vert:ED,meshmatcap_frag:MD,meshnormal_vert:TD,meshnormal_frag:AD,meshphong_vert:CD,meshphong_frag:$D,meshphysical_vert:RD,meshphysical_frag:ID,meshtoon_vert:PD,meshtoon_frag:kD,points_vert:OD,points_frag:DD,shadow_vert:LD,shadow_frag:zD,sprite_vert:ND,sprite_frag:UD},Oe={common:{diffuse:{value:new qt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Lt},alphaMap:{value:null},alphaMapTransform:{value:new Lt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Lt}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Lt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Lt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Lt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Lt},normalScale:{value:new kt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Lt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Lt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Lt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Lt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new qt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new qt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Lt},alphaTest:{value:0},uvTransform:{value:new Lt}},sprite:{diffuse:{value:new qt(16777215)},opacity:{value:1},center:{value:new kt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Lt},alphaMap:{value:null},alphaMapTransform:{value:new Lt},alphaTest:{value:0}}},Hr={basic:{uniforms:Vn([Oe.common,Oe.specularmap,Oe.envmap,Oe.aomap,Oe.lightmap,Oe.fog]),vertexShader:Pt.meshbasic_vert,fragmentShader:Pt.meshbasic_frag},lambert:{uniforms:Vn([Oe.common,Oe.specularmap,Oe.envmap,Oe.aomap,Oe.lightmap,Oe.emissivemap,Oe.bumpmap,Oe.normalmap,Oe.displacementmap,Oe.fog,Oe.lights,{emissive:{value:new qt(0)}}]),vertexShader:Pt.meshlambert_vert,fragmentShader:Pt.meshlambert_frag},phong:{uniforms:Vn([Oe.common,Oe.specularmap,Oe.envmap,Oe.aomap,Oe.lightmap,Oe.emissivemap,Oe.bumpmap,Oe.normalmap,Oe.displacementmap,Oe.fog,Oe.lights,{emissive:{value:new qt(0)},specular:{value:new qt(1118481)},shininess:{value:30}}]),vertexShader:Pt.meshphong_vert,fragmentShader:Pt.meshphong_frag},standard:{uniforms:Vn([Oe.common,Oe.envmap,Oe.aomap,Oe.lightmap,Oe.emissivemap,Oe.bumpmap,Oe.normalmap,Oe.displacementmap,Oe.roughnessmap,Oe.metalnessmap,Oe.fog,Oe.lights,{emissive:{value:new qt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Pt.meshphysical_vert,fragmentShader:Pt.meshphysical_frag},toon:{uniforms:Vn([Oe.common,Oe.aomap,Oe.lightmap,Oe.emissivemap,Oe.bumpmap,Oe.normalmap,Oe.displacementmap,Oe.gradientmap,Oe.fog,Oe.lights,{emissive:{value:new qt(0)}}]),vertexShader:Pt.meshtoon_vert,fragmentShader:Pt.meshtoon_frag},matcap:{uniforms:Vn([Oe.common,Oe.bumpmap,Oe.normalmap,Oe.displacementmap,Oe.fog,{matcap:{value:null}}]),vertexShader:Pt.meshmatcap_vert,fragmentShader:Pt.meshmatcap_frag},points:{uniforms:Vn([Oe.points,Oe.fog]),vertexShader:Pt.points_vert,fragmentShader:Pt.points_frag},dashed:{uniforms:Vn([Oe.common,Oe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Pt.linedashed_vert,fragmentShader:Pt.linedashed_frag},depth:{uniforms:Vn([Oe.common,Oe.displacementmap]),vertexShader:Pt.depth_vert,fragmentShader:Pt.depth_frag},normal:{uniforms:Vn([Oe.common,Oe.bumpmap,Oe.normalmap,Oe.displacementmap,{opacity:{value:1}}]),vertexShader:Pt.meshnormal_vert,fragmentShader:Pt.meshnormal_frag},sprite:{uniforms:Vn([Oe.sprite,Oe.fog]),vertexShader:Pt.sprite_vert,fragmentShader:Pt.sprite_frag},background:{uniforms:{uvTransform:{value:new Lt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Pt.background_vert,fragmentShader:Pt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:Pt.backgroundCube_vert,fragmentShader:Pt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Pt.cube_vert,fragmentShader:Pt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Pt.equirect_vert,fragmentShader:Pt.equirect_frag},distanceRGBA:{uniforms:Vn([Oe.common,Oe.displacementmap,{referencePosition:{value:new re},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Pt.distanceRGBA_vert,fragmentShader:Pt.distanceRGBA_frag},shadow:{uniforms:Vn([Oe.lights,Oe.fog,{color:{value:new qt(0)},opacity:{value:1}}]),vertexShader:Pt.shadow_vert,fragmentShader:Pt.shadow_frag}};Hr.physical={uniforms:Vn([Hr.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Lt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Lt},clearcoatNormalScale:{value:new kt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Lt},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Lt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Lt},sheen:{value:0},sheenColor:{value:new qt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Lt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Lt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Lt},transmissionSamplerSize:{value:new kt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Lt},attenuationDistance:{value:0},attenuationColor:{value:new qt(0)},specularColor:{value:new qt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Lt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Lt},anisotropyVector:{value:new kt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Lt}}]),vertexShader:Pt.meshphysical_vert,fragmentShader:Pt.meshphysical_frag};const ml={r:0,b:0,g:0};function BD(n,e,t,r,i,a,s){const o=new qt(0);let l=a===!0?0:1,u,c,h=null,p=0,d=null;function m(g,_){let w=!1,b=_.isScene===!0?_.background:null;b&&b.isTexture&&(b=(_.backgroundBlurriness>0?t:e).get(b)),b===null?y(o,l):b&&b.isColor&&(y(b,1),w=!0);const E=n.xr.getEnvironmentBlendMode();E==="additive"?r.buffers.color.setClear(0,0,0,1,s):E==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,s),(n.autoClear||w)&&n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil),b&&(b.isCubeTexture||b.mapping===hu)?(c===void 0&&(c=new hi(new Ao(1,1,1),new va({name:"BackgroundCubeMaterial",uniforms:ps(Hr.backgroundCube.uniforms),vertexShader:Hr.backgroundCube.vertexShader,fragmentShader:Hr.backgroundCube.fragmentShader,side:rr,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(T,I,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(c)),c.material.uniforms.envMap.value=b,c.material.uniforms.flipEnvMap.value=b.isCubeTexture&&b.isRenderTargetTexture===!1?-1:1,c.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,c.material.toneMapped=Qt.getTransfer(b.colorSpace)!==rn,(h!==b||p!==b.version||d!==n.toneMapping)&&(c.material.needsUpdate=!0,h=b,p=b.version,d=n.toneMapping),c.layers.enableAll(),g.unshift(c,c.geometry,c.material,0,0,null)):b&&b.isTexture&&(u===void 0&&(u=new hi(new mu(2,2),new va({name:"BackgroundMaterial",uniforms:ps(Hr.background.uniforms),vertexShader:Hr.background.vertexShader,fragmentShader:Hr.background.fragmentShader,side:Ui,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),Object.defineProperty(u.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(u)),u.material.uniforms.t2D.value=b,u.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,u.material.toneMapped=Qt.getTransfer(b.colorSpace)!==rn,b.matrixAutoUpdate===!0&&b.updateMatrix(),u.material.uniforms.uvTransform.value.copy(b.matrix),(h!==b||p!==b.version||d!==n.toneMapping)&&(u.material.needsUpdate=!0,h=b,p=b.version,d=n.toneMapping),u.layers.enableAll(),g.unshift(u,u.geometry,u.material,0,0,null))}function y(g,_){g.getRGB(ml,Ux(n)),r.buffers.color.setClear(ml.r,ml.g,ml.b,_,s)}return{getClearColor:function(){return o},setClearColor:function(g,_=1){o.set(g),l=_,y(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(g){l=g,y(o,l)},render:m}}function FD(n,e,t,r){const i=n.getParameter(n.MAX_VERTEX_ATTRIBS),a=r.isWebGL2?null:e.get("OES_vertex_array_object"),s=r.isWebGL2||a!==null,o={},l=g(null);let u=l,c=!1;function h(F,$,L,H,K){let X=!1;if(s){const J=y(H,L,$);u!==J&&(u=J,d(u.object)),X=_(F,H,L,K),X&&w(F,H,L,K)}else{const J=$.wireframe===!0;(u.geometry!==H.id||u.program!==L.id||u.wireframe!==J)&&(u.geometry=H.id,u.program=L.id,u.wireframe=J,X=!0)}K!==null&&t.update(K,n.ELEMENT_ARRAY_BUFFER),(X||c)&&(c=!1,B(F,$,L,H),K!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t.get(K).buffer))}function p(){return r.isWebGL2?n.createVertexArray():a.createVertexArrayOES()}function d(F){return r.isWebGL2?n.bindVertexArray(F):a.bindVertexArrayOES(F)}function m(F){return r.isWebGL2?n.deleteVertexArray(F):a.deleteVertexArrayOES(F)}function y(F,$,L){const H=L.wireframe===!0;let K=o[F.id];K===void 0&&(K={},o[F.id]=K);let X=K[$.id];X===void 0&&(X={},K[$.id]=X);let J=X[H];return J===void 0&&(J=g(p()),X[H]=J),J}function g(F){const $=[],L=[],H=[];for(let K=0;K=0){const de=K[ae];let ye=X[ae];if(ye===void 0&&(ae==="instanceMatrix"&&F.instanceMatrix&&(ye=F.instanceMatrix),ae==="instanceColor"&&F.instanceColor&&(ye=F.instanceColor)),de===void 0||de.attribute!==ye||ye&&de.data!==ye.data)return!0;J++}return u.attributesNum!==J||u.index!==H}function w(F,$,L,H){const K={},X=$.attributes;let J=0;const W=L.getAttributes();for(const ae in W)if(W[ae].location>=0){let de=X[ae];de===void 0&&(ae==="instanceMatrix"&&F.instanceMatrix&&(de=F.instanceMatrix),ae==="instanceColor"&&F.instanceColor&&(de=F.instanceColor));const ye={};ye.attribute=de,de&&de.data&&(ye.data=de.data),K[ae]=ye,J++}u.attributes=K,u.attributesNum=J,u.index=H}function b(){const F=u.newAttributes;for(let $=0,L=F.length;$=0){let Z=K[W];if(Z===void 0&&(W==="instanceMatrix"&&F.instanceMatrix&&(Z=F.instanceMatrix),W==="instanceColor"&&F.instanceColor&&(Z=F.instanceColor)),Z!==void 0){const de=Z.normalized,ye=Z.itemSize,Pe=t.get(Z);if(Pe===void 0)continue;const ke=Pe.buffer,Be=Pe.type,et=Pe.bytesPerElement,De=r.isWebGL2===!0&&(Be===n.INT||Be===n.UNSIGNED_INT||Z.gpuType===vx);if(Z.isInterleavedBufferAttribute){const Xe=Z.data,te=Xe.stride,Xt=Z.offset;if(Xe.isInstancedInterleavedBuffer){for(let Fe=0;Fe0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const s=typeof WebGL2RenderingContext<"u"&&n.constructor.name==="WebGL2RenderingContext";let o=t.precision!==void 0?t.precision:"highp";const l=a(o);l!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",l,"instead."),o=l);const u=s||e.has("WEBGL_draw_buffers"),c=t.logarithmicDepthBuffer===!0,h=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),d=n.getParameter(n.MAX_TEXTURE_SIZE),m=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),y=n.getParameter(n.MAX_VERTEX_ATTRIBS),g=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),_=n.getParameter(n.MAX_VARYING_VECTORS),w=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),b=p>0,E=s||e.has("OES_texture_float"),T=b&&E,I=s?n.getParameter(n.MAX_SAMPLES):0;return{isWebGL2:s,drawBuffers:u,getMaxAnisotropy:i,getMaxPrecision:a,precision:o,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:p,maxTextureSize:d,maxCubemapSize:m,maxAttributes:y,maxVertexUniforms:g,maxVaryings:_,maxFragmentUniforms:w,vertexTextures:b,floatFragmentTextures:E,floatVertexTextures:T,maxSamples:I}}function VD(n){const e=this;let t=null,r=0,i=!1,a=!1;const s=new Ri,o=new Lt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,p){const d=h.length!==0||p||r!==0||i;return i=p,r=h.length,d},this.beginShadows=function(){a=!0,c(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(h,p){t=c(h,p,0)},this.setState=function(h,p,d){const m=h.clippingPlanes,y=h.clipIntersection,g=h.clipShadows,_=n.get(h);if(!i||m===null||m.length===0||a&&!g)a?c(null):u();else{const w=a?0:r,b=w*4;let E=_.clippingState||null;l.value=E,E=c(m,p,b,d);for(let T=0;T!==b;++T)E[T]=t[T];_.clippingState=E,this.numIntersection=y?this.numPlanes:0,this.numPlanes+=w}};function u(){l.value!==t&&(l.value=t,l.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function c(h,p,d,m){const y=h!==null?h.length:0;let g=null;if(y!==0){if(g=l.value,m!==!0||g===null){const _=d+y*4,w=p.matrixWorldInverse;o.getNormalMatrix(w),(g===null||g.length<_)&&(g=new Float32Array(_));for(let b=0,E=d;b!==y;++b,E+=4)s.copy(h[b]).applyMatrix4(w,o),s.normal.toArray(g,E),g[E+3]=s.constant}l.value=g,l.needsUpdate=!0}return e.numPlanes=y,e.numIntersection=0,g}}function HD(n){let e=new WeakMap;function t(s,o){return o===rd?s.mapping=cs:o===id&&(s.mapping=ds),s}function r(s){if(s&&s.isTexture){const o=s.mapping;if(o===rd||o===id)if(e.has(s)){const l=e.get(s).texture;return t(l,s.mapping)}else{const l=s.image;if(l&&l.height>0){const u=new rk(l.height/2);return u.fromEquirectangularTexture(n,s),e.set(s,u),s.addEventListener("dispose",i),t(u.texture,s.mapping)}else return null}}return s}function i(s){const o=s.target;o.removeEventListener("dispose",i);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:r,dispose:a}}class qD extends Bx{constructor(e=-1,t=1,r=1,i=-1,a=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=r,this.bottom=i,this.near=a,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,r,i,a,s){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=a,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let a=r-e,s=r+e,o=i+t,l=i-t;if(this.view!==null&&this.view.enabled){const u=(this.right-this.left)/this.view.fullWidth/this.zoom,c=(this.top-this.bottom)/this.view.fullHeight/this.zoom;a+=u*this.view.offsetX,s=a+u*this.view.width,o-=c*this.view.offsetY,l=o-c*this.view.height}this.projectionMatrix.makeOrthographic(a,s,o,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const ns=4,c_=[.125,.215,.35,.446,.526,.582],ia=20,Ic=new qD,d_=new qt;let Pc=null,kc=0,Oc=0;const Ji=(1+Math.sqrt(5))/2,Ka=1/Ji,h_=[new re(1,1,1),new re(-1,1,1),new re(1,1,-1),new re(-1,1,-1),new re(0,Ji,Ka),new re(0,Ji,-Ka),new re(Ka,0,Ji),new re(-Ka,0,Ji),new re(Ji,Ka,0),new re(-Ji,Ka,0)];class p_{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,r=.1,i=100){Pc=this._renderer.getRenderTarget(),kc=this._renderer.getActiveCubeFace(),Oc=this._renderer.getActiveMipmapLevel(),this._setSize(256);const a=this._allocateTargets();return a.depthBuffer=!0,this._sceneToCubeUV(e,r,i,a),t>0&&this._blur(a,0,0,t),this._applyPMREM(a),this._cleanup(a),a}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=g_(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=m_(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?b:0,b,b),c.setRenderTarget(i),y&&c.render(m,o),c.render(e,o)}m.geometry.dispose(),m.material.dispose(),c.toneMapping=p,c.autoClear=h,e.background=g}_textureToCubeUV(e,t){const r=this._renderer,i=e.mapping===cs||e.mapping===ds;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=g_()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=m_());const a=i?this._cubemapMaterial:this._equirectMaterial,s=new hi(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;gl(t,0,0,3*l,2*l),r.setRenderTarget(t),r.render(s,Ic)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;for(let i=1;iia&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${ia}`);const _=[];let w=0;for(let C=0;Cb-ns?i-b+ns:0),I=4*(this._cubeSize-E);gl(t,T,I,3*E,2*E),l.setRenderTarget(t),l.render(h,Ic)}}function jD(n){const e=[],t=[],r=[];let i=n;const a=n-ns+1+c_.length;for(let s=0;sn-ns?l=c_[s-n+ns-1]:s===0&&(l=0),r.push(l);const u=1/(o-2),c=-u,h=1+u,p=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,m=6,y=3,g=2,_=1,w=new Float32Array(y*m*d),b=new Float32Array(g*m*d),E=new Float32Array(_*m*d);for(let I=0;I2?0:-1,R=[C,B,0,C+2/3,B,0,C+2/3,B+1,0,C,B,0,C+2/3,B+1,0,C,B+1,0];w.set(R,y*m*I),b.set(p,g*m*I);const k=[I,I,I,I,I,I];E.set(k,_*m*I)}const T=new Ma;T.setAttribute("position",new Yr(w,y)),T.setAttribute("uv",new Yr(b,g)),T.setAttribute("faceIndex",new Yr(E,_)),e.push(T),i>ns&&i--}return{lodPlanes:e,sizeLods:t,sigmas:r}}function f_(n,e,t){const r=new _a(n,e,t);return r.texture.mapping=hu,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function gl(n,e,t,r,i){n.viewport.set(e,t,r,i),n.scissor.set(e,t,r,i)}function XD(n,e,t){const r=new Float32Array(ia),i=new re(0,1,0);return new va({name:"SphericalGaussianBlur",defines:{n:ia,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:sh(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:Oi,depthTest:!1,depthWrite:!1})}function m_(){return new va({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:sh(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:Oi,depthTest:!1,depthWrite:!1})}function g_(){return new va({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:sh(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:Oi,depthTest:!1,depthWrite:!1})}function sh(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}function YD(n){let e=new WeakMap,t=null;function r(o){if(o&&o.isTexture){const l=o.mapping,u=l===rd||l===id,c=l===cs||l===ds;if(u||c)if(o.isRenderTargetTexture&&o.needsPMREMUpdate===!0){o.needsPMREMUpdate=!1;let h=e.get(o);return t===null&&(t=new p_(n)),h=u?t.fromEquirectangular(o,h):t.fromCubemap(o,h),e.set(o,h),h.texture}else{if(e.has(o))return e.get(o).texture;{const h=o.image;if(u&&h&&h.height>0||c&&h&&i(h)){t===null&&(t=new p_(n));const p=u?t.fromEquirectangular(o):t.fromCubemap(o);return e.set(o,p),o.addEventListener("dispose",a),p.texture}else return null}}}return o}function i(o){let l=0;const u=6;for(let c=0;ce.maxTextureSize&&(k=Math.ceil(R/e.maxTextureSize),R=e.maxTextureSize);const j=new Float32Array(R*k*4*m),Q=new Px(j,R,k,m);Q.type=ki,Q.needsUpdate=!0;const ie=B*4;for(let $=0;$0)return n;const i=e*t;let a=__[i];if(a===void 0&&(a=new Float32Array(i),__[i]=a),e!==0){r.toArray(a,0);for(let s=1,o=0;s!==e;++s)o+=t,n[s].toArray(a,o)}return a}function wn(n,e){if(n.length!==e.length)return!1;for(let t=0,r=n.length;t":" "} ${o}: ${t[s]}`)}return r.join(` `)}function ZL(n){const e=Qt.getPrimaries(Qt.workingColorSpace),t=Qt.getPrimaries(n);let r;switch(e===t?r="":e===Yl&&t===Xl?r="LinearDisplayP3ToLinearSRGB":e===Xl&&t===Yl&&(r="LinearSRGBToLinearDisplayP3"),n){case fi:case pu:return[r,"LinearTransferOETF"];case En:case rh:return[r,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",n),[r,"LinearTransferOETF"]}}function E_(n,e,t){const r=n.getShaderParameter(e,n.COMPILE_STATUS),i=n.getShaderInfoLog(e).trim();if(r&&i==="")return"";const a=/ERROR: 0:(\d+)/.exec(i);if(a){const s=parseInt(a[1]);return t.toUpperCase()+` `+i+` `+KL(n.getShaderSource(e),s)}else return i}function QL(n,e){const t=ZL(e);return`vec4 ${n}( vec4 value ) { return ${t[0]}( ${t[1]}( value ) ); }`}function JL(n,e){let t;switch(e){case YI:t="Linear";break;case KI:t="Reinhard";break;case ZI:t="OptimizedCineon";break;case QI:t="ACESFilmic";break;case eP:t="AgX";break;case JI:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function ez(n){return[n.extensionDerivatives||n.envMapCubeUVHeight||n.bumpMap||n.normalMapTangentSpace||n.clearcoatNormalMap||n.flatShading||n.shaderID==="physical"?"#extension GL_OES_standard_derivatives : enable":"",(n.extensionFragDepth||n.logarithmicDepthBuffer)&&n.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",n.extensionDrawBuffers&&n.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(n.extensionShaderTextureLOD||n.envMap||n.transmission)&&n.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(rs).join(` `)}function tz(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":""].filter(rs).join(` `)}function nz(n){const e=[];for(const t in n){const r=n[t];r!==!1&&e.push("#define "+t+" "+r)}return e.join(` `)}function rz(n,e){const t={},r=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function ud(n){return n.replace(iz,sz)}const az=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function sz(n,e){let t=Pt[e];if(t===void 0){const r=az.get(e);if(r!==void 0)t=Pt[r],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return ud(t)}const oz=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function A_(n){return n.replace(oz,lz)}function lz(n,e,t,r){let i="";for(let a=parseInt(e);a0&&(_+=` `),w=[d,"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,y].filter(rs).join(` `),w.length>0&&(w+=` `)):(_=[C_(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,y,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors&&t.isWebGL2?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` `].filter(rs).join(` `),w=[d,C_(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,y,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Di?"#define TONE_MAPPING":"",t.toneMapping!==Di?Pt.tonemapping_pars_fragment:"",t.toneMapping!==Di?JL("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Pt.colorspace_pars_fragment,QL("linearToOutputTexel",t.outputColorSpace),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(rs).join(` `)),s=ud(s),s=M_(s,t),s=T_(s,t),o=ud(o),o=M_(o,t),o=T_(o,t),s=A_(s),o=A_(o),t.isWebGL2&&t.isRawShaderMaterial!==!0&&(b=`#version 300 es `,_=[m,"precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+_,w=["precision mediump sampler2DArray;","#define varying in",t.glslVersion===qg?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===qg?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` `+w);const E=b+_+s,T=b+w+o,I=S_(i,i.VERTEX_SHADER,E),C=S_(i,i.FRAGMENT_SHADER,T);i.attachShader(g,I),i.attachShader(g,C),t.index0AttributeName!==void 0?i.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(g,0,"position"),i.linkProgram(g);function B(Q){if(n.debug.checkShaderErrors){const ie=i.getProgramInfoLog(g).trim(),F=i.getShaderInfoLog(I).trim(),$=i.getShaderInfoLog(C).trim();let L=!0,H=!0;if(i.getProgramParameter(g,i.LINK_STATUS)===!1)if(L=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(i,g,I,C);else{const K=E_(i,I,"vertex"),X=E_(i,C,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(g,i.VALIDATE_STATUS)+` Program Info Log: `+ie+` `+K+` `+X)}else ie!==""?console.warn("THREE.WebGLProgram: Program Info Log:",ie):(F===""||$==="")&&(H=!1);H&&(Q.diagnostics={runnable:L,programLog:ie,vertexShader:{log:F,prefix:_},fragmentShader:{log:$,prefix:w}})}i.deleteShader(I),i.deleteShader(C),R=new Cl(i,g),k=rz(i,g)}let R;this.getUniforms=function(){return R===void 0&&B(this),R};let k;this.getAttributes=function(){return k===void 0&&B(this),k};let j=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return j===!1&&(j=i.getProgramParameter(g,XL)),j},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=YL++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=I,this.fragmentShader=C,this}let mz=0;class gz{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(t),a=this._getShaderStage(r),s=this._getShaderCacheForMaterial(e);return s.has(i)===!1&&(s.add(i),i.usedTimes++),s.has(a)===!1&&(s.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const r of t)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let r=t.get(e);return r===void 0&&(r=new Set,t.set(e,r)),r}_getShaderStage(e){const t=this.shaderCache;let r=t.get(e);return r===void 0&&(r=new _z(e),t.set(e,r)),r}}class _z{constructor(e){this.id=mz++,this.code=e,this.usedTimes=0}}function yz(n,e,t,r,i,a,s){const o=new Ox,l=new gz,u=[],c=i.isWebGL2,h=i.logarithmicDepthBuffer,p=i.vertexTextures;let d=i.precision;const m={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function y(R){return R===0?"uv":`uv${R}`}function g(R,k,j,Q,ie){const F=Q.fog,$=ie.geometry,L=R.isMeshStandardMaterial?Q.environment:null,H=(R.isMeshStandardMaterial?t:e).get(R.envMap||L),K=H&&H.mapping===hu?H.image.height:null,X=m[R.type];R.precision!==null&&(d=i.getMaxPrecision(R.precision),d!==R.precision&&console.warn("THREE.WebGLProgram.getParameters:",R.precision,"not supported, using",d,"instead."));const J=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,W=J!==void 0?J.length:0;let ae=0;$.morphAttributes.position!==void 0&&(ae=1),$.morphAttributes.normal!==void 0&&(ae=2),$.morphAttributes.color!==void 0&&(ae=3);let Z,de,ye,Pe;if(X){const Jt=Hr[X];Z=Jt.vertexShader,de=Jt.fragmentShader}else Z=R.vertexShader,de=R.fragmentShader,l.update(R),ye=l.getVertexShaderID(R),Pe=l.getFragmentShaderID(R);const ke=n.getRenderTarget(),Be=ie.isInstancedMesh===!0,et=ie.isBatchedMesh===!0,De=!!R.map,Xe=!!R.matcap,te=!!H,Xt=!!R.aoMap,Fe=!!R.lightMap,ot=!!R.bumpMap,Ve=!!R.normalMap,zt=!!R.displacementMap,xt=!!R.emissiveMap,N=!!R.metalnessMap,O=!!R.roughnessMap,ne=R.anisotropy>0,ge=R.clearcoat>0,we=R.iridescence>0,_e=R.sheen>0,Ye=R.transmission>0,Re=ne&&!!R.anisotropyMap,We=ge&&!!R.clearcoatMap,nt=ge&&!!R.clearcoatNormalMap,dt=ge&&!!R.clearcoatRoughnessMap,be=we&&!!R.iridescenceMap,yt=we&&!!R.iridescenceThicknessMap,vt=_e&&!!R.sheenColorMap,ht=_e&&!!R.sheenRoughnessMap,Ue=!!R.specularMap,Le=!!R.specularColorMap,U=!!R.specularIntensityMap,ve=Ye&&!!R.transmissionMap,Ze=Ye&&!!R.thicknessMap,He=!!R.gradientMap,Se=!!R.alphaMap,q=R.alphaTest>0,fe=!!R.alphaHash,Ie=!!R.extensions,lt=!!$.attributes.uv1,it=!!$.attributes.uv2,Ct=!!$.attributes.uv3;let $t=Di;return R.toneMapped&&(ke===null||ke.isXRRenderTarget===!0)&&($t=n.toneMapping),{isWebGL2:c,shaderID:X,shaderType:R.type,shaderName:R.name,vertexShader:Z,fragmentShader:de,defines:R.defines,customVertexShaderID:ye,customFragmentShaderID:Pe,isRawShaderMaterial:R.isRawShaderMaterial===!0,glslVersion:R.glslVersion,precision:d,batching:et,instancing:Be,instancingColor:Be&&ie.instanceColor!==null,supportsVertexTextures:p,outputColorSpace:ke===null?n.outputColorSpace:ke.isXRRenderTarget===!0?ke.texture.colorSpace:fi,map:De,matcap:Xe,envMap:te,envMapMode:te&&H.mapping,envMapCubeUVHeight:K,aoMap:Xt,lightMap:Fe,bumpMap:ot,normalMap:Ve,displacementMap:p&&zt,emissiveMap:xt,normalMapObjectSpace:Ve&&R.normalMapType===hP,normalMapTangentSpace:Ve&&R.normalMapType===Ax,metalnessMap:N,roughnessMap:O,anisotropy:ne,anisotropyMap:Re,clearcoat:ge,clearcoatMap:We,clearcoatNormalMap:nt,clearcoatRoughnessMap:dt,iridescence:we,iridescenceMap:be,iridescenceThicknessMap:yt,sheen:_e,sheenColorMap:vt,sheenRoughnessMap:ht,specularMap:Ue,specularColorMap:Le,specularIntensityMap:U,transmission:Ye,transmissionMap:ve,thicknessMap:Ze,gradientMap:He,opaque:R.transparent===!1&&R.blending===is,alphaMap:Se,alphaTest:q,alphaHash:fe,combine:R.combine,mapUv:De&&y(R.map.channel),aoMapUv:Xt&&y(R.aoMap.channel),lightMapUv:Fe&&y(R.lightMap.channel),bumpMapUv:ot&&y(R.bumpMap.channel),normalMapUv:Ve&&y(R.normalMap.channel),displacementMapUv:zt&&y(R.displacementMap.channel),emissiveMapUv:xt&&y(R.emissiveMap.channel),metalnessMapUv:N&&y(R.metalnessMap.channel),roughnessMapUv:O&&y(R.roughnessMap.channel),anisotropyMapUv:Re&&y(R.anisotropyMap.channel),clearcoatMapUv:We&&y(R.clearcoatMap.channel),clearcoatNormalMapUv:nt&&y(R.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:dt&&y(R.clearcoatRoughnessMap.channel),iridescenceMapUv:be&&y(R.iridescenceMap.channel),iridescenceThicknessMapUv:yt&&y(R.iridescenceThicknessMap.channel),sheenColorMapUv:vt&&y(R.sheenColorMap.channel),sheenRoughnessMapUv:ht&&y(R.sheenRoughnessMap.channel),specularMapUv:Ue&&y(R.specularMap.channel),specularColorMapUv:Le&&y(R.specularColorMap.channel),specularIntensityMapUv:U&&y(R.specularIntensityMap.channel),transmissionMapUv:ve&&y(R.transmissionMap.channel),thicknessMapUv:Ze&&y(R.thicknessMap.channel),alphaMapUv:Se&&y(R.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(Ve||ne),vertexColors:R.vertexColors,vertexAlphas:R.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,vertexUv1s:lt,vertexUv2s:it,vertexUv3s:Ct,pointsUvs:ie.isPoints===!0&&!!$.attributes.uv&&(De||Se),fog:!!F,useFog:R.fog===!0,fogExp2:F&&F.isFogExp2,flatShading:R.flatShading===!0,sizeAttenuation:R.sizeAttenuation===!0,logarithmicDepthBuffer:h,skinning:ie.isSkinnedMesh===!0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:W,morphTextureStride:ae,numDirLights:k.directional.length,numPointLights:k.point.length,numSpotLights:k.spot.length,numSpotLightMaps:k.spotLightMap.length,numRectAreaLights:k.rectArea.length,numHemiLights:k.hemi.length,numDirLightShadows:k.directionalShadowMap.length,numPointLightShadows:k.pointShadowMap.length,numSpotLightShadows:k.spotShadowMap.length,numSpotLightShadowsWithMaps:k.numSpotLightShadowsWithMaps,numLightProbes:k.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:R.dithering,shadowMapEnabled:n.shadowMap.enabled&&j.length>0,shadowMapType:n.shadowMap.type,toneMapping:$t,useLegacyLights:n._useLegacyLights,decodeVideoTexture:De&&R.map.isVideoTexture===!0&&Qt.getTransfer(R.map.colorSpace)===rn,premultipliedAlpha:R.premultipliedAlpha,doubleSided:R.side===qr,flipSided:R.side===rr,useDepthPacking:R.depthPacking>=0,depthPacking:R.depthPacking||0,index0AttributeName:R.index0AttributeName,extensionDerivatives:Ie&&R.extensions.derivatives===!0,extensionFragDepth:Ie&&R.extensions.fragDepth===!0,extensionDrawBuffers:Ie&&R.extensions.drawBuffers===!0,extensionShaderTextureLOD:Ie&&R.extensions.shaderTextureLOD===!0,extensionClipCullDistance:Ie&&R.extensions.clipCullDistance&&r.has("WEBGL_clip_cull_distance"),rendererExtensionFragDepth:c||r.has("EXT_frag_depth"),rendererExtensionDrawBuffers:c||r.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:c||r.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:R.customProgramCacheKey()}}function _(R){const k=[];if(R.shaderID?k.push(R.shaderID):(k.push(R.customVertexShaderID),k.push(R.customFragmentShaderID)),R.defines!==void 0)for(const j in R.defines)k.push(j),k.push(R.defines[j]);return R.isRawShaderMaterial===!1&&(w(k,R),b(k,R),k.push(n.outputColorSpace)),k.push(R.customProgramCacheKey),k.join()}function w(R,k){R.push(k.precision),R.push(k.outputColorSpace),R.push(k.envMapMode),R.push(k.envMapCubeUVHeight),R.push(k.mapUv),R.push(k.alphaMapUv),R.push(k.lightMapUv),R.push(k.aoMapUv),R.push(k.bumpMapUv),R.push(k.normalMapUv),R.push(k.displacementMapUv),R.push(k.emissiveMapUv),R.push(k.metalnessMapUv),R.push(k.roughnessMapUv),R.push(k.anisotropyMapUv),R.push(k.clearcoatMapUv),R.push(k.clearcoatNormalMapUv),R.push(k.clearcoatRoughnessMapUv),R.push(k.iridescenceMapUv),R.push(k.iridescenceThicknessMapUv),R.push(k.sheenColorMapUv),R.push(k.sheenRoughnessMapUv),R.push(k.specularMapUv),R.push(k.specularColorMapUv),R.push(k.specularIntensityMapUv),R.push(k.transmissionMapUv),R.push(k.thicknessMapUv),R.push(k.combine),R.push(k.fogExp2),R.push(k.sizeAttenuation),R.push(k.morphTargetsCount),R.push(k.morphAttributeCount),R.push(k.numDirLights),R.push(k.numPointLights),R.push(k.numSpotLights),R.push(k.numSpotLightMaps),R.push(k.numHemiLights),R.push(k.numRectAreaLights),R.push(k.numDirLightShadows),R.push(k.numPointLightShadows),R.push(k.numSpotLightShadows),R.push(k.numSpotLightShadowsWithMaps),R.push(k.numLightProbes),R.push(k.shadowMapType),R.push(k.toneMapping),R.push(k.numClippingPlanes),R.push(k.numClipIntersection),R.push(k.depthPacking)}function b(R,k){o.disableAll(),k.isWebGL2&&o.enable(0),k.supportsVertexTextures&&o.enable(1),k.instancing&&o.enable(2),k.instancingColor&&o.enable(3),k.matcap&&o.enable(4),k.envMap&&o.enable(5),k.normalMapObjectSpace&&o.enable(6),k.normalMapTangentSpace&&o.enable(7),k.clearcoat&&o.enable(8),k.iridescence&&o.enable(9),k.alphaTest&&o.enable(10),k.vertexColors&&o.enable(11),k.vertexAlphas&&o.enable(12),k.vertexUv1s&&o.enable(13),k.vertexUv2s&&o.enable(14),k.vertexUv3s&&o.enable(15),k.vertexTangents&&o.enable(16),k.anisotropy&&o.enable(17),k.alphaHash&&o.enable(18),k.batching&&o.enable(19),R.push(o.mask),o.disableAll(),k.fog&&o.enable(0),k.useFog&&o.enable(1),k.flatShading&&o.enable(2),k.logarithmicDepthBuffer&&o.enable(3),k.skinning&&o.enable(4),k.morphTargets&&o.enable(5),k.morphNormals&&o.enable(6),k.morphColors&&o.enable(7),k.premultipliedAlpha&&o.enable(8),k.shadowMapEnabled&&o.enable(9),k.useLegacyLights&&o.enable(10),k.doubleSided&&o.enable(11),k.flipSided&&o.enable(12),k.useDepthPacking&&o.enable(13),k.dithering&&o.enable(14),k.transmission&&o.enable(15),k.sheen&&o.enable(16),k.opaque&&o.enable(17),k.pointsUvs&&o.enable(18),k.decodeVideoTexture&&o.enable(19),R.push(o.mask)}function E(R){const k=m[R.type];let j;if(k){const Q=Hr[k];j=JP.clone(Q.uniforms)}else j=R.uniforms;return j}function T(R,k){let j;for(let Q=0,ie=u.length;Q0?r.push(_):d.transparent===!0?i.push(_):t.push(_)}function l(h,p,d,m,y,g){const _=s(h,p,d,m,y,g);d.transmission>0?r.unshift(_):d.transparent===!0?i.unshift(_):t.unshift(_)}function u(h,p){t.length>1&&t.sort(h||wz),r.length>1&&r.sort(p||$_),i.length>1&&i.sort(p||$_)}function c(){for(let h=e,p=n.length;h=a.length?(s=new R_,a.push(s)):s=a[i],s}function t(){n=new WeakMap}return{get:e,dispose:t}}function xz(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new re,color:new qt};break;case"SpotLight":t={position:new re,direction:new re,color:new qt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new re,color:new qt,distance:0,decay:0};break;case"HemisphereLight":t={direction:new re,skyColor:new qt,groundColor:new qt};break;case"RectAreaLight":t={color:new qt,position:new re,halfWidth:new re,halfHeight:new re};break}return n[e.id]=t,t}}}function Sz(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new kt};break;case"SpotLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new kt};break;case"PointLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new kt,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let Ez=0;function Mz(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function Tz(n,e){const t=new xz,r=Sz(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new re);const a=new re,s=new In,o=new In;function l(c,h){let p=0,d=0,m=0;for(let Q=0;Q<9;Q++)i.probe[Q].set(0,0,0);let y=0,g=0,_=0,w=0,b=0,E=0,T=0,I=0,C=0,B=0,R=0;c.sort(Mz);const k=h===!0?Math.PI:1;for(let Q=0,ie=c.length;Q0&&(e.isWebGL2?n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Oe.LTC_FLOAT_1,i.rectAreaLTC2=Oe.LTC_FLOAT_2):(i.rectAreaLTC1=Oe.LTC_HALF_1,i.rectAreaLTC2=Oe.LTC_HALF_2):n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Oe.LTC_FLOAT_1,i.rectAreaLTC2=Oe.LTC_FLOAT_2):n.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=Oe.LTC_HALF_1,i.rectAreaLTC2=Oe.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),i.ambient[0]=p,i.ambient[1]=d,i.ambient[2]=m;const j=i.hash;(j.directionalLength!==y||j.pointLength!==g||j.spotLength!==_||j.rectAreaLength!==w||j.hemiLength!==b||j.numDirectionalShadows!==E||j.numPointShadows!==T||j.numSpotShadows!==I||j.numSpotMaps!==C||j.numLightProbes!==R)&&(i.directional.length=y,i.spot.length=_,i.rectArea.length=w,i.point.length=g,i.hemi.length=b,i.directionalShadow.length=E,i.directionalShadowMap.length=E,i.pointShadow.length=T,i.pointShadowMap.length=T,i.spotShadow.length=I,i.spotShadowMap.length=I,i.directionalShadowMatrix.length=E,i.pointShadowMatrix.length=T,i.spotLightMatrix.length=I+C-B,i.spotLightMap.length=C,i.numSpotLightShadowsWithMaps=B,i.numLightProbes=R,j.directionalLength=y,j.pointLength=g,j.spotLength=_,j.rectAreaLength=w,j.hemiLength=b,j.numDirectionalShadows=E,j.numPointShadows=T,j.numSpotShadows=I,j.numSpotMaps=C,j.numLightProbes=R,i.version=Ez++)}function u(c,h){let p=0,d=0,m=0,y=0,g=0;const _=h.matrixWorldInverse;for(let w=0,b=c.length;w=o.length?(l=new I_(n,e),o.push(l)):l=o[s],l}function i(){t=new WeakMap}return{get:r,dispose:i}}class Cz extends To{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=cP,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class $z extends To{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const Rz=`void main() { gl_Position = vec4( position, 1.0 ); }`,Iz=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; #include void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); }`;function Pz(n,e,t){let r=new Gx;const i=new kt,a=new kt,s=new $n,o=new Cz({depthPacking:dP}),l=new $z,u={},c=t.maxTextureSize,h={[Ui]:rr,[rr]:Ui,[qr]:qr},p=new va({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new kt},radius:{value:4}},vertexShader:Rz,fragmentShader:Iz}),d=p.clone();d.defines.HORIZONTAL_PASS=1;const m=new Ma;m.setAttribute("position",new Yr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const y=new hi(m,p),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=gx;let _=this.type;this.render=function(I,C,B){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||I.length===0)return;const R=n.getRenderTarget(),k=n.getActiveCubeFace(),j=n.getActiveMipmapLevel(),Q=n.state;Q.setBlending(Oi),Q.buffers.color.setClear(1,1,1,1),Q.buffers.depth.setTest(!0),Q.setScissorTest(!1);const ie=_!==li&&this.type===li,F=_===li&&this.type!==li;for(let $=0,L=I.length;$c||i.y>c)&&(i.x>c&&(a.x=Math.floor(c/X.x),i.x=a.x*X.x,K.mapSize.x=a.x),i.y>c&&(a.y=Math.floor(c/X.y),i.y=a.y*X.y,K.mapSize.y=a.y)),K.map===null||ie===!0||F===!0){const W=this.type!==li?{minFilter:qn,magFilter:qn}:{};K.map!==null&&K.map.dispose(),K.map=new _a(i.x,i.y,W),K.map.texture.name=H.name+".shadowMap",K.camera.updateProjectionMatrix()}n.setRenderTarget(K.map),n.clear();const J=K.getViewportCount();for(let W=0;W0||C.map&&C.alphaTest>0){const Q=k.uuid,ie=C.uuid;let F=u[Q];F===void 0&&(F={},u[Q]=F);let $=F[ie];$===void 0&&($=k.clone(),F[ie]=$,C.addEventListener("dispose",T)),k=$}if(k.visible=C.visible,k.wireframe=C.wireframe,R===li?k.side=C.shadowSide!==null?C.shadowSide:C.side:k.side=C.shadowSide!==null?C.shadowSide:h[C.side],k.alphaMap=C.alphaMap,k.alphaTest=C.alphaTest,k.map=C.map,k.clipShadows=C.clipShadows,k.clippingPlanes=C.clippingPlanes,k.clipIntersection=C.clipIntersection,k.displacementMap=C.displacementMap,k.displacementScale=C.displacementScale,k.displacementBias=C.displacementBias,k.wireframeLinewidth=C.wireframeLinewidth,k.linewidth=C.linewidth,B.isPointLight===!0&&k.isMeshDistanceMaterial===!0){const Q=n.properties.get(k);Q.light=B}return k}function E(I,C,B,R,k){if(I.visible===!1)return;if(I.layers.test(C.layers)&&(I.isMesh||I.isLine||I.isPoints)&&(I.castShadow||I.receiveShadow&&k===li)&&(!I.frustumCulled||r.intersectsObject(I))){I.modelViewMatrix.multiplyMatrices(B.matrixWorldInverse,I.matrixWorld);const ie=e.update(I),F=I.material;if(Array.isArray(F)){const $=ie.groups;for(let L=0,H=$.length;L=1):J.indexOf("OpenGL ES")!==-1&&(X=parseFloat(/^OpenGL ES (\d)/.exec(J)[1]),K=X>=2);let W=null,ae={};const Z=n.getParameter(n.SCISSOR_BOX),de=n.getParameter(n.VIEWPORT),ye=new $n().fromArray(Z),Pe=new $n().fromArray(de);function ke(q,fe,Ie,lt){const it=new Uint8Array(4),Ct=n.createTexture();n.bindTexture(q,Ct),n.texParameteri(q,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(q,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let $t=0;$t"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new WeakMap;let h;const p=new WeakMap;let d=!1;try{d=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(N,O){return d?new OffscreenCanvas(N,O):io("canvas")}function y(N,O,ne,ge){let we=1;if((N.width>ge||N.height>ge)&&(we=ge/Math.max(N.width,N.height)),we<1||O===!0)if(typeof HTMLImageElement<"u"&&N instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&N instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&N instanceof ImageBitmap){const _e=O?Zl:Math.floor,Ye=_e(we*N.width),Re=_e(we*N.height);h===void 0&&(h=m(Ye,Re));const We=ne?m(Ye,Re):h;return We.width=Ye,We.height=Re,We.getContext("2d").drawImage(N,0,0,Ye,Re),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+N.width+"x"+N.height+") to ("+Ye+"x"+Re+")."),We}else return"data"in N&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+N.width+"x"+N.height+")."),N;return N}function g(N){return ld(N.width)&&ld(N.height)}function _(N){return o?!1:N.wrapS!==Lr||N.wrapT!==Lr||N.minFilter!==qn&&N.minFilter!==mr}function w(N,O){return N.generateMipmaps&&O&&N.minFilter!==qn&&N.minFilter!==mr}function b(N){n.generateMipmap(N)}function E(N,O,ne,ge,we=!1){if(o===!1)return O;if(N!==null){if(n[N]!==void 0)return n[N];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+N+"'")}let _e=O;if(O===n.RED&&(ne===n.FLOAT&&(_e=n.R32F),ne===n.HALF_FLOAT&&(_e=n.R16F),ne===n.UNSIGNED_BYTE&&(_e=n.R8)),O===n.RED_INTEGER&&(ne===n.UNSIGNED_BYTE&&(_e=n.R8UI),ne===n.UNSIGNED_SHORT&&(_e=n.R16UI),ne===n.UNSIGNED_INT&&(_e=n.R32UI),ne===n.BYTE&&(_e=n.R8I),ne===n.SHORT&&(_e=n.R16I),ne===n.INT&&(_e=n.R32I)),O===n.RG&&(ne===n.FLOAT&&(_e=n.RG32F),ne===n.HALF_FLOAT&&(_e=n.RG16F),ne===n.UNSIGNED_BYTE&&(_e=n.RG8)),O===n.RGBA){const Ye=we?jl:Qt.getTransfer(ge);ne===n.FLOAT&&(_e=n.RGBA32F),ne===n.HALF_FLOAT&&(_e=n.RGBA16F),ne===n.UNSIGNED_BYTE&&(_e=Ye===rn?n.SRGB8_ALPHA8:n.RGBA8),ne===n.UNSIGNED_SHORT_4_4_4_4&&(_e=n.RGBA4),ne===n.UNSIGNED_SHORT_5_5_5_1&&(_e=n.RGB5_A1)}return(_e===n.R16F||_e===n.R32F||_e===n.RG16F||_e===n.RG32F||_e===n.RGBA16F||_e===n.RGBA32F)&&e.get("EXT_color_buffer_float"),_e}function T(N,O,ne){return w(N,ne)===!0||N.isFramebufferTexture&&N.minFilter!==qn&&N.minFilter!==mr?Math.log2(Math.max(O.width,O.height))+1:N.mipmaps!==void 0&&N.mipmaps.length>0?N.mipmaps.length:N.isCompressedTexture&&Array.isArray(N.image)?O.mipmaps.length:1}function I(N){return N===qn||N===yg||N===lc?n.NEAREST:n.LINEAR}function C(N){const O=N.target;O.removeEventListener("dispose",C),R(O),O.isVideoTexture&&c.delete(O)}function B(N){const O=N.target;O.removeEventListener("dispose",B),j(O)}function R(N){const O=r.get(N);if(O.__webglInit===void 0)return;const ne=N.source,ge=p.get(ne);if(ge){const we=ge[O.__cacheKey];we.usedTimes--,we.usedTimes===0&&k(N),Object.keys(ge).length===0&&p.delete(ne)}r.remove(N)}function k(N){const O=r.get(N);n.deleteTexture(O.__webglTexture);const ne=N.source,ge=p.get(ne);delete ge[O.__cacheKey],s.memory.textures--}function j(N){const O=N.texture,ne=r.get(N),ge=r.get(O);if(ge.__webglTexture!==void 0&&(n.deleteTexture(ge.__webglTexture),s.memory.textures--),N.depthTexture&&N.depthTexture.dispose(),N.isWebGLCubeRenderTarget)for(let we=0;we<6;we++){if(Array.isArray(ne.__webglFramebuffer[we]))for(let _e=0;_e=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+N+" texture units while this GPU supports only "+i.maxTextures),Q+=1,N}function $(N){const O=[];return O.push(N.wrapS),O.push(N.wrapT),O.push(N.wrapR||0),O.push(N.magFilter),O.push(N.minFilter),O.push(N.anisotropy),O.push(N.internalFormat),O.push(N.format),O.push(N.type),O.push(N.generateMipmaps),O.push(N.premultiplyAlpha),O.push(N.flipY),O.push(N.unpackAlignment),O.push(N.colorSpace),O.join()}function L(N,O){const ne=r.get(N);if(N.isVideoTexture&&zt(N),N.isRenderTargetTexture===!1&&N.version>0&&ne.__version!==N.version){const ge=N.image;if(ge===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(ge.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{ye(ne,N,O);return}}t.bindTexture(n.TEXTURE_2D,ne.__webglTexture,n.TEXTURE0+O)}function H(N,O){const ne=r.get(N);if(N.version>0&&ne.__version!==N.version){ye(ne,N,O);return}t.bindTexture(n.TEXTURE_2D_ARRAY,ne.__webglTexture,n.TEXTURE0+O)}function K(N,O){const ne=r.get(N);if(N.version>0&&ne.__version!==N.version){ye(ne,N,O);return}t.bindTexture(n.TEXTURE_3D,ne.__webglTexture,n.TEXTURE0+O)}function X(N,O){const ne=r.get(N);if(N.version>0&&ne.__version!==N.version){Pe(ne,N,O);return}t.bindTexture(n.TEXTURE_CUBE_MAP,ne.__webglTexture,n.TEXTURE0+O)}const J={[ad]:n.REPEAT,[Lr]:n.CLAMP_TO_EDGE,[sd]:n.MIRRORED_REPEAT},W={[qn]:n.NEAREST,[yg]:n.NEAREST_MIPMAP_NEAREST,[lc]:n.NEAREST_MIPMAP_LINEAR,[mr]:n.LINEAR,[tP]:n.LINEAR_MIPMAP_NEAREST,[to]:n.LINEAR_MIPMAP_LINEAR},ae={[pP]:n.NEVER,[vP]:n.ALWAYS,[fP]:n.LESS,[Cx]:n.LEQUAL,[mP]:n.EQUAL,[yP]:n.GEQUAL,[gP]:n.GREATER,[_P]:n.NOTEQUAL};function Z(N,O,ne){if(ne?(n.texParameteri(N,n.TEXTURE_WRAP_S,J[O.wrapS]),n.texParameteri(N,n.TEXTURE_WRAP_T,J[O.wrapT]),(N===n.TEXTURE_3D||N===n.TEXTURE_2D_ARRAY)&&n.texParameteri(N,n.TEXTURE_WRAP_R,J[O.wrapR]),n.texParameteri(N,n.TEXTURE_MAG_FILTER,W[O.magFilter]),n.texParameteri(N,n.TEXTURE_MIN_FILTER,W[O.minFilter])):(n.texParameteri(N,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(N,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),(N===n.TEXTURE_3D||N===n.TEXTURE_2D_ARRAY)&&n.texParameteri(N,n.TEXTURE_WRAP_R,n.CLAMP_TO_EDGE),(O.wrapS!==Lr||O.wrapT!==Lr)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),n.texParameteri(N,n.TEXTURE_MAG_FILTER,I(O.magFilter)),n.texParameteri(N,n.TEXTURE_MIN_FILTER,I(O.minFilter)),O.minFilter!==qn&&O.minFilter!==mr&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),O.compareFunction&&(n.texParameteri(N,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(N,n.TEXTURE_COMPARE_FUNC,ae[O.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const ge=e.get("EXT_texture_filter_anisotropic");if(O.magFilter===qn||O.minFilter!==lc&&O.minFilter!==to||O.type===ki&&e.has("OES_texture_float_linear")===!1||o===!1&&O.type===no&&e.has("OES_texture_half_float_linear")===!1)return;(O.anisotropy>1||r.get(O).__currentAnisotropy)&&(n.texParameterf(N,ge.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(O.anisotropy,i.getMaxAnisotropy())),r.get(O).__currentAnisotropy=O.anisotropy)}}function de(N,O){let ne=!1;N.__webglInit===void 0&&(N.__webglInit=!0,O.addEventListener("dispose",C));const ge=O.source;let we=p.get(ge);we===void 0&&(we={},p.set(ge,we));const _e=$(O);if(_e!==N.__cacheKey){we[_e]===void 0&&(we[_e]={texture:n.createTexture(),usedTimes:0},s.memory.textures++,ne=!0),we[_e].usedTimes++;const Ye=we[N.__cacheKey];Ye!==void 0&&(we[N.__cacheKey].usedTimes--,Ye.usedTimes===0&&k(O)),N.__cacheKey=_e,N.__webglTexture=we[_e].texture}return ne}function ye(N,O,ne){let ge=n.TEXTURE_2D;(O.isDataArrayTexture||O.isCompressedArrayTexture)&&(ge=n.TEXTURE_2D_ARRAY),O.isData3DTexture&&(ge=n.TEXTURE_3D);const we=de(N,O),_e=O.source;t.bindTexture(ge,N.__webglTexture,n.TEXTURE0+ne);const Ye=r.get(_e);if(_e.version!==Ye.__version||we===!0){t.activeTexture(n.TEXTURE0+ne);const Re=Qt.getPrimaries(Qt.workingColorSpace),We=O.colorSpace===_r?null:Qt.getPrimaries(O.colorSpace),nt=O.colorSpace===_r||Re===We?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,O.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,O.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,O.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,nt);const dt=_(O)&&g(O.image)===!1;let be=y(O.image,dt,!1,i.maxTextureSize);be=xt(O,be);const yt=g(be)||o,vt=a.convert(O.format,O.colorSpace);let ht=a.convert(O.type),Ue=E(O.internalFormat,vt,ht,O.colorSpace,O.isVideoTexture);Z(ge,O,yt);let Le;const U=O.mipmaps,ve=o&&O.isVideoTexture!==!0&&Ue!==Mx,Ze=Ye.__version===void 0||we===!0,He=T(O,be,yt);if(O.isDepthTexture)Ue=n.DEPTH_COMPONENT,o?O.type===ki?Ue=n.DEPTH_COMPONENT32F:O.type===Pi?Ue=n.DEPTH_COMPONENT24:O.type===ua?Ue=n.DEPTH24_STENCIL8:Ue=n.DEPTH_COMPONENT16:O.type===ki&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),O.format===ca&&Ue===n.DEPTH_COMPONENT&&O.type!==nh&&O.type!==Pi&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),O.type=Pi,ht=a.convert(O.type)),O.format===hs&&Ue===n.DEPTH_COMPONENT&&(Ue=n.DEPTH_STENCIL,O.type!==ua&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),O.type=ua,ht=a.convert(O.type))),Ze&&(ve?t.texStorage2D(n.TEXTURE_2D,1,Ue,be.width,be.height):t.texImage2D(n.TEXTURE_2D,0,Ue,be.width,be.height,0,vt,ht,null));else if(O.isDataTexture)if(U.length>0&&yt){ve&&Ze&&t.texStorage2D(n.TEXTURE_2D,He,Ue,U[0].width,U[0].height);for(let Se=0,q=U.length;Se>=1,q>>=1}}else if(U.length>0&&yt){ve&&Ze&&t.texStorage2D(n.TEXTURE_2D,He,Ue,U[0].width,U[0].height);for(let Se=0,q=U.length;Se0&&Ze++,t.texStorage2D(n.TEXTURE_CUBE_MAP,Ze,Le,be[0].width,be[0].height));for(let Se=0;Se<6;Se++)if(dt){U?t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Se,0,0,0,be[Se].width,be[Se].height,ht,Ue,be[Se].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Se,0,Le,be[Se].width,be[Se].height,0,ht,Ue,be[Se].data);for(let q=0;q>_e),be=Math.max(1,O.height>>_e);we===n.TEXTURE_3D||we===n.TEXTURE_2D_ARRAY?t.texImage3D(we,_e,We,dt,be,O.depth,0,Ye,Re,null):t.texImage2D(we,_e,We,dt,be,0,Ye,Re,null)}t.bindFramebuffer(n.FRAMEBUFFER,N),Ve(O)?l.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,ge,we,r.get(ne).__webglTexture,0,ot(O)):(we===n.TEXTURE_2D||we>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&we<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,ge,we,r.get(ne).__webglTexture,_e),t.bindFramebuffer(n.FRAMEBUFFER,null)}function Be(N,O,ne){if(n.bindRenderbuffer(n.RENDERBUFFER,N),O.depthBuffer&&!O.stencilBuffer){let ge=o===!0?n.DEPTH_COMPONENT24:n.DEPTH_COMPONENT16;if(ne||Ve(O)){const we=O.depthTexture;we&&we.isDepthTexture&&(we.type===ki?ge=n.DEPTH_COMPONENT32F:we.type===Pi&&(ge=n.DEPTH_COMPONENT24));const _e=ot(O);Ve(O)?l.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,_e,ge,O.width,O.height):n.renderbufferStorageMultisample(n.RENDERBUFFER,_e,ge,O.width,O.height)}else n.renderbufferStorage(n.RENDERBUFFER,ge,O.width,O.height);n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,N)}else if(O.depthBuffer&&O.stencilBuffer){const ge=ot(O);ne&&Ve(O)===!1?n.renderbufferStorageMultisample(n.RENDERBUFFER,ge,n.DEPTH24_STENCIL8,O.width,O.height):Ve(O)?l.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,ge,n.DEPTH24_STENCIL8,O.width,O.height):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,O.width,O.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,N)}else{const ge=O.isWebGLMultipleRenderTargets===!0?O.texture:[O.texture];for(let we=0;we0){ne.__webglFramebuffer[Re]=[];for(let We=0;We0){ne.__webglFramebuffer=[];for(let Re=0;Re0&&Ve(N)===!1){const Re=_e?O:[O];ne.__webglMultisampledFramebuffer=n.createFramebuffer(),ne.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,ne.__webglMultisampledFramebuffer);for(let We=0;We0)for(let We=0;We0)for(let We=0;We0&&Ve(N)===!1){const O=N.isWebGLMultipleRenderTargets?N.texture:[N.texture],ne=N.width,ge=N.height;let we=n.COLOR_BUFFER_BIT;const _e=[],Ye=N.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Re=r.get(N),We=N.isWebGLMultipleRenderTargets===!0;if(We)for(let nt=0;nt0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&O.__useRenderToTexture!==!1}function zt(N){const O=s.render.frame;c.get(N)!==O&&(c.set(N,O),N.update())}function xt(N,O){const ne=N.colorSpace,ge=N.format,we=N.type;return N.isCompressedTexture===!0||N.isVideoTexture===!0||N.format===od||ne!==fi&&ne!==_r&&(Qt.getTransfer(ne)===rn?o===!1?e.has("EXT_sRGB")===!0&&ge===zr?(N.format=od,N.minFilter=mr,N.generateMipmaps=!1):O=Rx.sRGBToLinear(O):(ge!==zr||we!==Li)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ne)),O}this.allocateTextureUnit=F,this.resetTextureUnits=ie,this.setTexture2D=L,this.setTexture2DArray=H,this.setTexture3D=K,this.setTextureCube=X,this.rebindTextures=Xe,this.setupRenderTarget=te,this.updateRenderTargetMipmap=Xt,this.updateMultisampleRenderTarget=Fe,this.setupDepthRenderbuffer=De,this.setupFrameBufferTexture=ke,this.useMultisampledRTT=Ve}function Dz(n,e,t){const r=t.isWebGL2;function i(a,s=_r){let o;const l=Qt.getTransfer(s);if(a===Li)return n.UNSIGNED_BYTE;if(a===wx)return n.UNSIGNED_SHORT_4_4_4_4;if(a===bx)return n.UNSIGNED_SHORT_5_5_5_1;if(a===nP)return n.BYTE;if(a===rP)return n.SHORT;if(a===nh)return n.UNSIGNED_SHORT;if(a===vx)return n.INT;if(a===Pi)return n.UNSIGNED_INT;if(a===ki)return n.FLOAT;if(a===no)return r?n.HALF_FLOAT:(o=e.get("OES_texture_half_float"),o!==null?o.HALF_FLOAT_OES:null);if(a===iP)return n.ALPHA;if(a===zr)return n.RGBA;if(a===aP)return n.LUMINANCE;if(a===sP)return n.LUMINANCE_ALPHA;if(a===ca)return n.DEPTH_COMPONENT;if(a===hs)return n.DEPTH_STENCIL;if(a===od)return o=e.get("EXT_sRGB"),o!==null?o.SRGB_ALPHA_EXT:null;if(a===oP)return n.RED;if(a===xx)return n.RED_INTEGER;if(a===lP)return n.RG;if(a===Sx)return n.RG_INTEGER;if(a===Ex)return n.RGBA_INTEGER;if(a===uc||a===cc||a===dc||a===hc)if(l===rn)if(o=e.get("WEBGL_compressed_texture_s3tc_srgb"),o!==null){if(a===uc)return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(a===cc)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(a===dc)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(a===hc)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(o=e.get("WEBGL_compressed_texture_s3tc"),o!==null){if(a===uc)return o.COMPRESSED_RGB_S3TC_DXT1_EXT;if(a===cc)return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(a===dc)return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(a===hc)return o.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(a===vg||a===wg||a===bg||a===xg)if(o=e.get("WEBGL_compressed_texture_pvrtc"),o!==null){if(a===vg)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(a===wg)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(a===bg)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(a===xg)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(a===Mx)return o=e.get("WEBGL_compressed_texture_etc1"),o!==null?o.COMPRESSED_RGB_ETC1_WEBGL:null;if(a===Sg||a===Eg)if(o=e.get("WEBGL_compressed_texture_etc"),o!==null){if(a===Sg)return l===rn?o.COMPRESSED_SRGB8_ETC2:o.COMPRESSED_RGB8_ETC2;if(a===Eg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:o.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(a===Mg||a===Tg||a===Ag||a===Cg||a===$g||a===Rg||a===Ig||a===Pg||a===kg||a===Og||a===Dg||a===Lg||a===zg||a===Ng)if(o=e.get("WEBGL_compressed_texture_astc"),o!==null){if(a===Mg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:o.COMPRESSED_RGBA_ASTC_4x4_KHR;if(a===Tg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:o.COMPRESSED_RGBA_ASTC_5x4_KHR;if(a===Ag)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:o.COMPRESSED_RGBA_ASTC_5x5_KHR;if(a===Cg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:o.COMPRESSED_RGBA_ASTC_6x5_KHR;if(a===$g)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:o.COMPRESSED_RGBA_ASTC_6x6_KHR;if(a===Rg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:o.COMPRESSED_RGBA_ASTC_8x5_KHR;if(a===Ig)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:o.COMPRESSED_RGBA_ASTC_8x6_KHR;if(a===Pg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:o.COMPRESSED_RGBA_ASTC_8x8_KHR;if(a===kg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:o.COMPRESSED_RGBA_ASTC_10x5_KHR;if(a===Og)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:o.COMPRESSED_RGBA_ASTC_10x6_KHR;if(a===Dg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:o.COMPRESSED_RGBA_ASTC_10x8_KHR;if(a===Lg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:o.COMPRESSED_RGBA_ASTC_10x10_KHR;if(a===zg)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:o.COMPRESSED_RGBA_ASTC_12x10_KHR;if(a===Ng)return l===rn?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:o.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(a===pc||a===Ug||a===Bg)if(o=e.get("EXT_texture_compression_bptc"),o!==null){if(a===pc)return l===rn?o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:o.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(a===Ug)return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(a===Bg)return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(a===uP||a===Fg||a===Gg||a===Wg)if(o=e.get("EXT_texture_compression_rgtc"),o!==null){if(a===pc)return o.COMPRESSED_RED_RGTC1_EXT;if(a===Fg)return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(a===Gg)return o.COMPRESSED_RED_GREEN_RGTC2_EXT;if(a===Wg)return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return a===ua?r?n.UNSIGNED_INT_24_8:(o=e.get("WEBGL_depth_texture"),o!==null?o.UNSIGNED_INT_24_8_WEBGL:null):n[a]!==void 0?n[a]:null}return{convert:i}}class Lz extends gr{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class _l extends ir{constructor(){super(),this.isGroup=!0,this.type="Group"}}const zz={type:"move"};class Lc{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new _l,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new _l,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new re,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new re),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new _l,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new re,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new re),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const r of e.hand.values())this._getHandJoint(t,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,r){let i=null,a=null,s=null;const o=this._targetRay,l=this._grip,u=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(u&&e.hand){s=!0;for(const y of e.hand.values()){const g=t.getJointPose(y,r),_=this._getHandJoint(u,y);g!==null&&(_.matrix.fromArray(g.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=g.radius),_.visible=g!==null}const c=u.joints["index-finger-tip"],h=u.joints["thumb-tip"],p=c.position.distanceTo(h.position),d=.02,m=.005;u.inputState.pinching&&p>d+m?(u.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!u.inputState.pinching&&p<=d-m&&(u.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,r),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(i=t.getPose(e.targetRaySpace,r),i===null&&a!==null&&(i=a),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(zz)))}return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=a!==null),u!==null&&(u.visible=s!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const r=new _l;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[t.jointName]=r,e.add(r)}return e.joints[t.jointName]}}class Nz extends Ea{constructor(e,t){super();const r=this;let i=null,a=1,s=null,o="local-floor",l=1,u=null,c=null,h=null,p=null,d=null,m=null;const y=t.getContextAttributes();let g=null,_=null;const w=[],b=[],E=new kt;let T=null;const I=new gr;I.layers.enable(1),I.viewport=new $n;const C=new gr;C.layers.enable(2),C.viewport=new $n;const B=[I,C],R=new Lz;R.layers.enable(1),R.layers.enable(2);let k=null,j=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let de=w[Z];return de===void 0&&(de=new Lc,w[Z]=de),de.getTargetRaySpace()},this.getControllerGrip=function(Z){let de=w[Z];return de===void 0&&(de=new Lc,w[Z]=de),de.getGripSpace()},this.getHand=function(Z){let de=w[Z];return de===void 0&&(de=new Lc,w[Z]=de),de.getHandSpace()};function Q(Z){const de=b.indexOf(Z.inputSource);if(de===-1)return;const ye=w[de];ye!==void 0&&(ye.update(Z.inputSource,Z.frame,u||s),ye.dispatchEvent({type:Z.type,data:Z.inputSource}))}function ie(){i.removeEventListener("select",Q),i.removeEventListener("selectstart",Q),i.removeEventListener("selectend",Q),i.removeEventListener("squeeze",Q),i.removeEventListener("squeezestart",Q),i.removeEventListener("squeezeend",Q),i.removeEventListener("end",ie),i.removeEventListener("inputsourceschange",F);for(let Z=0;Z=0&&(b[Pe]=null,w[Pe].disconnect(ye))}for(let de=0;de=b.length){b.push(ye),Pe=Be;break}else if(b[Be]===null){b[Be]=ye,Pe=Be;break}if(Pe===-1)break}const ke=w[Pe];ke&&ke.connect(ye)}}const $=new re,L=new re;function H(Z,de,ye){$.setFromMatrixPosition(de.matrixWorld),L.setFromMatrixPosition(ye.matrixWorld);const Pe=$.distanceTo(L),ke=de.projectionMatrix.elements,Be=ye.projectionMatrix.elements,et=ke[14]/(ke[10]-1),De=ke[14]/(ke[10]+1),Xe=(ke[9]+1)/ke[5],te=(ke[9]-1)/ke[5],Xt=(ke[8]-1)/ke[0],Fe=(Be[8]+1)/Be[0],ot=et*Xt,Ve=et*Fe,zt=Pe/(-Xt+Fe),xt=zt*-Xt;de.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(xt),Z.translateZ(zt),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert();const N=et+zt,O=De+zt,ne=ot-xt,ge=Ve+(Pe-xt),we=Xe*De/O*N,_e=te*De/O*N;Z.projectionMatrix.makePerspective(ne,ge,we,_e,N,O),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}function K(Z,de){de===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(de.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(i===null)return;R.near=C.near=I.near=Z.near,R.far=C.far=I.far=Z.far,(k!==R.near||j!==R.far)&&(i.updateRenderState({depthNear:R.near,depthFar:R.far}),k=R.near,j=R.far);const de=Z.parent,ye=R.cameras;K(R,de);for(let Pe=0;Pe0&&(g.alphaTest.value=_.alphaTest);const w=e.get(_).envMap;if(w&&(g.envMap.value=w,g.flipEnvMap.value=w.isCubeTexture&&w.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=_.reflectivity,g.ior.value=_.ior,g.refractionRatio.value=_.refractionRatio),_.lightMap){g.lightMap.value=_.lightMap;const b=n._useLegacyLights===!0?Math.PI:1;g.lightMapIntensity.value=_.lightMapIntensity*b,t(_.lightMap,g.lightMapTransform)}_.aoMap&&(g.aoMap.value=_.aoMap,g.aoMapIntensity.value=_.aoMapIntensity,t(_.aoMap,g.aoMapTransform))}function s(g,_){g.diffuse.value.copy(_.color),g.opacity.value=_.opacity,_.map&&(g.map.value=_.map,t(_.map,g.mapTransform))}function o(g,_){g.dashSize.value=_.dashSize,g.totalSize.value=_.dashSize+_.gapSize,g.scale.value=_.scale}function l(g,_,w,b){g.diffuse.value.copy(_.color),g.opacity.value=_.opacity,g.size.value=_.size*w,g.scale.value=b*.5,_.map&&(g.map.value=_.map,t(_.map,g.uvTransform)),_.alphaMap&&(g.alphaMap.value=_.alphaMap,t(_.alphaMap,g.alphaMapTransform)),_.alphaTest>0&&(g.alphaTest.value=_.alphaTest)}function u(g,_){g.diffuse.value.copy(_.color),g.opacity.value=_.opacity,g.rotation.value=_.rotation,_.map&&(g.map.value=_.map,t(_.map,g.mapTransform)),_.alphaMap&&(g.alphaMap.value=_.alphaMap,t(_.alphaMap,g.alphaMapTransform)),_.alphaTest>0&&(g.alphaTest.value=_.alphaTest)}function c(g,_){g.specular.value.copy(_.specular),g.shininess.value=Math.max(_.shininess,1e-4)}function h(g,_){_.gradientMap&&(g.gradientMap.value=_.gradientMap)}function p(g,_){g.metalness.value=_.metalness,_.metalnessMap&&(g.metalnessMap.value=_.metalnessMap,t(_.metalnessMap,g.metalnessMapTransform)),g.roughness.value=_.roughness,_.roughnessMap&&(g.roughnessMap.value=_.roughnessMap,t(_.roughnessMap,g.roughnessMapTransform)),e.get(_).envMap&&(g.envMapIntensity.value=_.envMapIntensity)}function d(g,_,w){g.ior.value=_.ior,_.sheen>0&&(g.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),g.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(g.sheenColorMap.value=_.sheenColorMap,t(_.sheenColorMap,g.sheenColorMapTransform)),_.sheenRoughnessMap&&(g.sheenRoughnessMap.value=_.sheenRoughnessMap,t(_.sheenRoughnessMap,g.sheenRoughnessMapTransform))),_.clearcoat>0&&(g.clearcoat.value=_.clearcoat,g.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(g.clearcoatMap.value=_.clearcoatMap,t(_.clearcoatMap,g.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,t(_.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(g.clearcoatNormalMap.value=_.clearcoatNormalMap,t(_.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===rr&&g.clearcoatNormalScale.value.negate())),_.iridescence>0&&(g.iridescence.value=_.iridescence,g.iridescenceIOR.value=_.iridescenceIOR,g.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(g.iridescenceMap.value=_.iridescenceMap,t(_.iridescenceMap,g.iridescenceMapTransform)),_.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=_.iridescenceThicknessMap,t(_.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),_.transmission>0&&(g.transmission.value=_.transmission,g.transmissionSamplerMap.value=w.texture,g.transmissionSamplerSize.value.set(w.width,w.height),_.transmissionMap&&(g.transmissionMap.value=_.transmissionMap,t(_.transmissionMap,g.transmissionMapTransform)),g.thickness.value=_.thickness,_.thicknessMap&&(g.thicknessMap.value=_.thicknessMap,t(_.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=_.attenuationDistance,g.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(g.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(g.anisotropyMap.value=_.anisotropyMap,t(_.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=_.specularIntensity,g.specularColor.value.copy(_.specularColor),_.specularColorMap&&(g.specularColorMap.value=_.specularColorMap,t(_.specularColorMap,g.specularColorMapTransform)),_.specularIntensityMap&&(g.specularIntensityMap.value=_.specularIntensityMap,t(_.specularIntensityMap,g.specularIntensityMapTransform))}function m(g,_){_.matcap&&(g.matcap.value=_.matcap)}function y(g,_){const w=e.get(_).light;g.referencePosition.value.setFromMatrixPosition(w.matrixWorld),g.nearDistance.value=w.shadow.camera.near,g.farDistance.value=w.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function Bz(n,e,t,r){let i={},a={},s=[];const o=t.isWebGL2?n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(w,b){const E=b.program;r.uniformBlockBinding(w,E)}function u(w,b){let E=i[w.id];E===void 0&&(m(w),E=c(w),i[w.id]=E,w.addEventListener("dispose",g));const T=b.program;r.updateUBOMapping(w,T);const I=e.render.frame;a[w.id]!==I&&(p(w),a[w.id]=I)}function c(w){const b=h();w.__bindingPointIndex=b;const E=n.createBuffer(),T=w.__size,I=w.usage;return n.bindBuffer(n.UNIFORM_BUFFER,E),n.bufferData(n.UNIFORM_BUFFER,T,I),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,b,E),E}function h(){for(let w=0;w0&&(E+=T-I),w.__size=E,w.__cache={},this}function y(w){const b={boundary:0,storage:0};return typeof w=="number"||typeof w=="boolean"?(b.boundary=4,b.storage=4):w.isVector2?(b.boundary=8,b.storage=8):w.isVector3||w.isColor?(b.boundary=16,b.storage=12):w.isVector4?(b.boundary=16,b.storage=16):w.isMatrix3?(b.boundary=48,b.storage=48):w.isMatrix4?(b.boundary=64,b.storage=64):w.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",w),b}function g(w){const b=w.target;b.removeEventListener("dispose",g);const E=s.indexOf(b.__bindingPointIndex);s.splice(E,1),n.deleteBuffer(i[b.id]),delete i[b.id],delete a[b.id]}function _(){for(const w in i)n.deleteBuffer(i[w]);s=[],i={},a={}}return{bind:l,update:u,dispose:_}}class Kx{constructor(e={}){const{canvas:t=DP(),context:r=null,depth:i=!0,stencil:a=!0,alpha:s=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:u=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1}=e;this.isWebGLRenderer=!0;let p;r!==null?p=r.getContextAttributes().alpha:p=s;const d=new Uint32Array(4),m=new Int32Array(4);let y=null,g=null;const _=[],w=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=En,this._useLegacyLights=!1,this.toneMapping=Di,this.toneMappingExposure=1;const b=this;let E=!1,T=0,I=0,C=null,B=-1,R=null;const k=new $n,j=new $n;let Q=null;const ie=new qt(0);let F=0,$=t.width,L=t.height,H=1,K=null,X=null;const J=new $n(0,0,$,L),W=new $n(0,0,$,L);let ae=!1;const Z=new Gx;let de=!1,ye=!1,Pe=null;const ke=new In,Be=new kt,et=new re,De={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Xe(){return C===null?H:1}let te=r;function Xt(z,ee){for(let oe=0;oe{function ze(){if(ue.forEach(function(qe){xt.get(qe).currentProgram.isReady()&&ue.delete(qe)}),ue.size===0){se(z);return}setTimeout(ze,10)}Fe.get("KHR_parallel_shader_compile")!==null?ze():setTimeout(ze,10)})};let $t=null;function Yt(z){$t&&$t(z)}function Jt(){Rt.stop()}function It(){Rt.start()}const Rt=new Wx;Rt.setAnimationLoop(Yt),typeof self<"u"&&Rt.setContext(self),this.setAnimationLoop=function(z){$t=z,He.setAnimationLoop(z),z===null?Rt.stop():Rt.start()},He.addEventListener("sessionstart",Jt),He.addEventListener("sessionend",It),this.render=function(z,ee){if(ee!==void 0&&ee.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(E===!0)return;z.matrixWorldAutoUpdate===!0&&z.updateMatrixWorld(),ee.parent===null&&ee.matrixWorldAutoUpdate===!0&&ee.updateMatrixWorld(),He.enabled===!0&&He.isPresenting===!0&&(He.cameraAutoUpdate===!0&&He.updateCamera(ee),ee=He.getCamera()),z.isScene===!0&&z.onBeforeRender(b,z,ee,C),g=nt.get(z,w.length),g.init(),w.push(g),ke.multiplyMatrices(ee.projectionMatrix,ee.matrixWorldInverse),Z.setFromProjectionMatrix(ke),ye=this.localClippingEnabled,de=dt.init(this.clippingPlanes,ye),y=We.get(z,_.length),y.init(),_.push(y),Fn(z,ee,0,b.sortObjects),y.finish(),b.sortObjects===!0&&y.sort(K,X),this.info.render.frame++,de===!0&&dt.beginShadows();const oe=g.state.shadowsArray;if(be.render(oe,z,ee),de===!0&&dt.endShadows(),this.info.autoReset===!0&&this.info.reset(),yt.render(y,z),g.setupLights(b._useLegacyLights),ee.isArrayCamera){const ue=ee.cameras;for(let se=0,ze=ue.length;se0?g=w[w.length-1]:g=null,_.pop(),_.length>0?y=_[_.length-1]:y=null};function Fn(z,ee,oe,ue){if(z.visible===!1)return;if(z.layers.test(ee.layers)){if(z.isGroup)oe=z.renderOrder;else if(z.isLOD)z.autoUpdate===!0&&z.update(ee);else if(z.isLight)g.pushLight(z),z.castShadow&&g.pushShadow(z);else if(z.isSprite){if(!z.frustumCulled||Z.intersectsSprite(z)){ue&&et.setFromMatrixPosition(z.matrixWorld).applyMatrix4(ke);const qe=_e.update(z),at=z.material;at.visible&&y.push(z,qe,at,oe,et.z,null)}}else if((z.isMesh||z.isLine||z.isPoints)&&(!z.frustumCulled||Z.intersectsObject(z))){const qe=_e.update(z),at=z.material;if(ue&&(z.boundingSphere!==void 0?(z.boundingSphere===null&&z.computeBoundingSphere(),et.copy(z.boundingSphere.center)):(qe.boundingSphere===null&&qe.computeBoundingSphere(),et.copy(qe.boundingSphere.center)),et.applyMatrix4(z.matrixWorld).applyMatrix4(ke)),Array.isArray(at)){const ft=qe.groups;for(let mt=0,wt=ft.length;mt0&&Pn(se,ze,ee,oe),ue&&Ve.viewport(k.copy(ue)),se.length>0&&Br(se,ee,oe),ze.length>0&&Br(ze,ee,oe),qe.length>0&&Br(qe,ee,oe),Ve.buffers.depth.setTest(!0),Ve.buffers.depth.setMask(!0),Ve.buffers.color.setMask(!0),Ve.setPolygonOffset(!1)}function Pn(z,ee,oe,ue){if((oe.isScene===!0?oe.overrideMaterial:null)!==null)return;const ze=ot.isWebGL2;Pe===null&&(Pe=new _a(1,1,{generateMipmaps:!0,type:Fe.has("EXT_color_buffer_half_float")?no:Li,minFilter:to,samples:ze?4:0})),b.getDrawingBufferSize(Be),ze?Pe.setSize(Be.x,Be.y):Pe.setSize(Zl(Be.x),Zl(Be.y));const qe=b.getRenderTarget();b.setRenderTarget(Pe),b.getClearColor(ie),F=b.getClearAlpha(),F<1&&b.setClearColor(16777215,.5),b.clear();const at=b.toneMapping;b.toneMapping=Di,Br(z,oe,ue),N.updateMultisampleRenderTarget(Pe),N.updateRenderTargetMipmap(Pe);let ft=!1;for(let mt=0,wt=ee.length;mt0),rt=!!oe.morphAttributes.position,en=!!oe.morphAttributes.normal,gn=!!oe.morphAttributes.color;let Wt=Di;ue.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(Wt=b.toneMapping);const kn=oe.morphAttributes.position||oe.morphAttributes.normal||oe.morphAttributes.color,Mt=kn!==void 0?kn.length:0,ut=xt.get(ue),xr=g.state.lights;if(de===!0&&(ye===!0||z!==R)){const Qe=z===R&&ue.id===B;dt.setState(ue,z,Qe)}let tn=!1;ue.version===ut.__version?(ut.needsLights&&ut.lightsStateVersion!==xr.state.version||ut.outputColorSpace!==at||se.isBatchedMesh&&ut.batching===!1||!se.isBatchedMesh&&ut.batching===!0||se.isInstancedMesh&&ut.instancing===!1||!se.isInstancedMesh&&ut.instancing===!0||se.isSkinnedMesh&&ut.skinning===!1||!se.isSkinnedMesh&&ut.skinning===!0||se.isInstancedMesh&&ut.instancingColor===!0&&se.instanceColor===null||se.isInstancedMesh&&ut.instancingColor===!1&&se.instanceColor!==null||ut.envMap!==ft||ue.fog===!0&&ut.fog!==ze||ut.numClippingPlanes!==void 0&&(ut.numClippingPlanes!==dt.numPlanes||ut.numIntersection!==dt.numIntersection)||ut.vertexAlphas!==mt||ut.vertexTangents!==wt||ut.morphTargets!==rt||ut.morphNormals!==en||ut.morphColors!==gn||ut.toneMapping!==Wt||ot.isWebGL2===!0&&ut.morphTargetsCount!==Mt)&&(tn=!0):(tn=!0,ut.__version=ue.version);let cr=ut.currentProgram;tn===!0&&(cr=Fr(ue,ee,se));let vi=!1,Qr=!1,wi=!1;const hn=cr.getUniforms(),Qn=ut.uniforms;if(Ve.useProgram(cr.program)&&(vi=!0,Qr=!0,wi=!0),ue.id!==B&&(B=ue.id,Qr=!0),vi||R!==z){hn.setValue(te,"projectionMatrix",z.projectionMatrix),hn.setValue(te,"viewMatrix",z.matrixWorldInverse);const Qe=hn.map.cameraPosition;Qe!==void 0&&Qe.setValue(te,et.setFromMatrixPosition(z.matrixWorld)),ot.logarithmicDepthBuffer&&hn.setValue(te,"logDepthBufFC",2/(Math.log(z.far+1)/Math.LN2)),(ue.isMeshPhongMaterial||ue.isMeshToonMaterial||ue.isMeshLambertMaterial||ue.isMeshBasicMaterial||ue.isMeshStandardMaterial||ue.isShaderMaterial)&&hn.setValue(te,"isOrthographic",z.isOrthographicCamera===!0),R!==z&&(R=z,Qr=!0,wi=!0)}if(se.isSkinnedMesh){hn.setOptional(te,se,"bindMatrix"),hn.setOptional(te,se,"bindMatrixInverse");const Qe=se.skeleton;Qe&&(ot.floatVertexTextures?(Qe.boneTexture===null&&Qe.computeBoneTexture(),hn.setValue(te,"boneTexture",Qe.boneTexture,N)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}se.isBatchedMesh&&(hn.setOptional(te,se,"batchingTexture"),hn.setValue(te,"batchingTexture",se._matricesTexture,N));const Fi=oe.morphAttributes;if((Fi.position!==void 0||Fi.normal!==void 0||Fi.color!==void 0&&ot.isWebGL2===!0)&&vt.update(se,oe,cr),(Qr||ut.receiveShadow!==se.receiveShadow)&&(ut.receiveShadow=se.receiveShadow,hn.setValue(te,"receiveShadow",se.receiveShadow)),ue.isMeshGouraudMaterial&&ue.envMap!==null&&(Qn.envMap.value=ft,Qn.flipEnvMap.value=ft.isCubeTexture&&ft.isRenderTargetTexture===!1?-1:1),Qr&&(hn.setValue(te,"toneMappingExposure",b.toneMappingExposure),ut.needsLights&&Ta(Qn,wi),ze&&ue.fog===!0&&Re.refreshFogUniforms(Qn,ze),Re.refreshMaterialUniforms(Qn,ue,H,L,Pe),Cl.upload(te,_i(ut),Qn,N)),ue.isShaderMaterial&&ue.uniformsNeedUpdate===!0&&(Cl.upload(te,_i(ut),Qn,N),ue.uniformsNeedUpdate=!1),ue.isSpriteMaterial&&hn.setValue(te,"center",se.center),hn.setValue(te,"modelViewMatrix",se.modelViewMatrix),hn.setValue(te,"normalMatrix",se.normalMatrix),hn.setValue(te,"modelMatrix",se.matrixWorld),ue.isShaderMaterial||ue.isRawShaderMaterial){const Qe=ue.uniformsGroups;for(let Jr=0,Gr=Qe.length;Jr0&&N.useMultisampledRTT(z)===!1?se=xt.get(z).__webglMultisampledFramebuffer:Array.isArray(wt)?se=wt[oe]:se=wt,k.copy(z.viewport),j.copy(z.scissor),Q=z.scissorTest}else k.copy(J).multiplyScalar(H).floor(),j.copy(W).multiplyScalar(H).floor(),Q=ae;if(Ve.bindFramebuffer(te.FRAMEBUFFER,se)&&ot.drawBuffers&&ue&&Ve.drawBuffers(z,se),Ve.viewport(k),Ve.scissor(j),Ve.setScissorTest(Q),ze){const ft=xt.get(z.texture);te.framebufferTexture2D(te.FRAMEBUFFER,te.COLOR_ATTACHMENT0,te.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ft.__webglTexture,oe)}else if(qe){const ft=xt.get(z.texture),mt=ee||0;te.framebufferTextureLayer(te.FRAMEBUFFER,te.COLOR_ATTACHMENT0,ft.__webglTexture,oe||0,mt)}B=-1},this.readRenderTargetPixels=function(z,ee,oe,ue,se,ze,qe){if(!(z&&z.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let at=xt.get(z).__webglFramebuffer;if(z.isWebGLCubeRenderTarget&&qe!==void 0&&(at=at[qe]),at){Ve.bindFramebuffer(te.FRAMEBUFFER,at);try{const ft=z.texture,mt=ft.format,wt=ft.type;if(mt!==zr&&Le.convert(mt)!==te.getParameter(te.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const rt=wt===no&&(Fe.has("EXT_color_buffer_half_float")||ot.isWebGL2&&Fe.has("EXT_color_buffer_float"));if(wt!==Li&&Le.convert(wt)!==te.getParameter(te.IMPLEMENTATION_COLOR_READ_TYPE)&&!(wt===ki&&(ot.isWebGL2||Fe.has("OES_texture_float")||Fe.has("WEBGL_color_buffer_float")))&&!rt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}ee>=0&&ee<=z.width-ue&&oe>=0&&oe<=z.height-se&&te.readPixels(ee,oe,ue,se,Le.convert(mt),Le.convert(wt),ze)}finally{const ft=C!==null?xt.get(C).__webglFramebuffer:null;Ve.bindFramebuffer(te.FRAMEBUFFER,ft)}}},this.copyFramebufferToTexture=function(z,ee,oe=0){const ue=Math.pow(2,-oe),se=Math.floor(ee.image.width*ue),ze=Math.floor(ee.image.height*ue);N.setTexture2D(ee,0),te.copyTexSubImage2D(te.TEXTURE_2D,oe,0,0,z.x,z.y,se,ze),Ve.unbindTexture()},this.copyTextureToTexture=function(z,ee,oe,ue=0){const se=ee.image.width,ze=ee.image.height,qe=Le.convert(oe.format),at=Le.convert(oe.type);N.setTexture2D(oe,0),te.pixelStorei(te.UNPACK_FLIP_Y_WEBGL,oe.flipY),te.pixelStorei(te.UNPACK_PREMULTIPLY_ALPHA_WEBGL,oe.premultiplyAlpha),te.pixelStorei(te.UNPACK_ALIGNMENT,oe.unpackAlignment),ee.isDataTexture?te.texSubImage2D(te.TEXTURE_2D,ue,z.x,z.y,se,ze,qe,at,ee.image.data):ee.isCompressedTexture?te.compressedTexSubImage2D(te.TEXTURE_2D,ue,z.x,z.y,ee.mipmaps[0].width,ee.mipmaps[0].height,qe,ee.mipmaps[0].data):te.texSubImage2D(te.TEXTURE_2D,ue,z.x,z.y,qe,at,ee.image),ue===0&&oe.generateMipmaps&&te.generateMipmap(te.TEXTURE_2D),Ve.unbindTexture()},this.copyTextureToTexture3D=function(z,ee,oe,ue,se=0){if(b.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const ze=z.max.x-z.min.x+1,qe=z.max.y-z.min.y+1,at=z.max.z-z.min.z+1,ft=Le.convert(ue.format),mt=Le.convert(ue.type);let wt;if(ue.isData3DTexture)N.setTexture3D(ue,0),wt=te.TEXTURE_3D;else if(ue.isDataArrayTexture||ue.isCompressedArrayTexture)N.setTexture2DArray(ue,0),wt=te.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}te.pixelStorei(te.UNPACK_FLIP_Y_WEBGL,ue.flipY),te.pixelStorei(te.UNPACK_PREMULTIPLY_ALPHA_WEBGL,ue.premultiplyAlpha),te.pixelStorei(te.UNPACK_ALIGNMENT,ue.unpackAlignment);const rt=te.getParameter(te.UNPACK_ROW_LENGTH),en=te.getParameter(te.UNPACK_IMAGE_HEIGHT),gn=te.getParameter(te.UNPACK_SKIP_PIXELS),Wt=te.getParameter(te.UNPACK_SKIP_ROWS),kn=te.getParameter(te.UNPACK_SKIP_IMAGES),Mt=oe.isCompressedTexture?oe.mipmaps[se]:oe.image;te.pixelStorei(te.UNPACK_ROW_LENGTH,Mt.width),te.pixelStorei(te.UNPACK_IMAGE_HEIGHT,Mt.height),te.pixelStorei(te.UNPACK_SKIP_PIXELS,z.min.x),te.pixelStorei(te.UNPACK_SKIP_ROWS,z.min.y),te.pixelStorei(te.UNPACK_SKIP_IMAGES,z.min.z),oe.isDataTexture||oe.isData3DTexture?te.texSubImage3D(wt,se,ee.x,ee.y,ee.z,ze,qe,at,ft,mt,Mt.data):oe.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),te.compressedTexSubImage3D(wt,se,ee.x,ee.y,ee.z,ze,qe,at,ft,Mt.data)):te.texSubImage3D(wt,se,ee.x,ee.y,ee.z,ze,qe,at,ft,mt,Mt),te.pixelStorei(te.UNPACK_ROW_LENGTH,rt),te.pixelStorei(te.UNPACK_IMAGE_HEIGHT,en),te.pixelStorei(te.UNPACK_SKIP_PIXELS,gn),te.pixelStorei(te.UNPACK_SKIP_ROWS,Wt),te.pixelStorei(te.UNPACK_SKIP_IMAGES,kn),se===0&&ue.generateMipmaps&&te.generateMipmap(wt),Ve.unbindTexture()},this.initTexture=function(z){z.isCubeTexture?N.setTextureCube(z,0):z.isData3DTexture?N.setTexture3D(z,0):z.isDataArrayTexture||z.isCompressedArrayTexture?N.setTexture2DArray(z,0):N.setTexture2D(z,0),Ve.unbindTexture()},this.resetState=function(){T=0,I=0,C=null,Ve.reset(),U.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return di}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===rh?"display-p3":"srgb",t.unpackColorSpace=Qt.workingColorSpace===pu?"display-p3":"srgb"}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===En?da:Tx}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===da?En:fi}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class Fz extends Kx{}Fz.prototype.isWebGL1Renderer=!0;class Gz extends ir{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t}}class Wz extends Xn{constructor(e,t,r,i,a,s,o,l,u){super(e,t,r,i,a,s,o,l,u),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Vz extends To{constructor(e){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new qt(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new qt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ax,this.normalScale=new kt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}const P_={enabled:!1,files:{},add:function(n,e){this.enabled!==!1&&(this.files[n]=e)},get:function(n){if(this.enabled!==!1)return this.files[n]},remove:function(n){delete this.files[n]},clear:function(){this.files={}}};class Hz{constructor(e,t,r){const i=this;let a=!1,s=0,o=0,l;const u=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=r,this.itemStart=function(c){o++,a===!1&&i.onStart!==void 0&&i.onStart(c,s,o),a=!0},this.itemEnd=function(c){s++,i.onProgress!==void 0&&i.onProgress(c,s,o),s===o&&(a=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(c){i.onError!==void 0&&i.onError(c)},this.resolveURL=function(c){return l?l(c):c},this.setURLModifier=function(c){return l=c,this},this.addHandler=function(c,h){return u.push(c,h),this},this.removeHandler=function(c){const h=u.indexOf(c);return h!==-1&&u.splice(h,2),this},this.getHandler=function(c){for(let h=0,p=u.length;hMath.PI&&(Ct-=fe),$t<-Math.PI?$t+=fe:$t>Math.PI&&($t-=fe),Ct<=$t?o.theta=Math.max(Ct,Math.min($t,o.theta)):o.theta=o.theta>(Ct+$t)/2?Math.max(Ct,o.theta):Math.min($t,o.theta)),o.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,o.phi)),o.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(c,r.dampingFactor):r.target.add(c),r.target.sub(r.cursor),r.target.clampLength(r.minTargetRadius,r.maxTargetRadius),r.target.add(r.cursor),r.zoomToCursor&&I||r.object.isOrthographicCamera?o.radius=J(o.radius):o.radius=J(o.radius*u),U.setFromSpherical(o),U.applyQuaternion(Ze),it.copy(r.target).add(U),r.object.lookAt(r.target),r.enableDamping===!0?(l.theta*=1-r.dampingFactor,l.phi*=1-r.dampingFactor,c.multiplyScalar(1-r.dampingFactor)):(l.set(0,0,0),c.set(0,0,0));let Yt=!1;if(r.zoomToCursor&&I){let Jt=null;if(r.object.isPerspectiveCamera){const It=U.length();Jt=J(It*u);const Rt=It-Jt;r.object.position.addScaledVector(E,Rt),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const It=new re(T.x,T.y,0);It.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/u)),r.object.updateProjectionMatrix(),Yt=!0;const Rt=new re(T.x,T.y,0);Rt.unproject(r.object),r.object.position.sub(Rt).add(It),r.object.updateMatrixWorld(),Jt=U.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;Jt!==null&&(this.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(Jt).add(r.object.position):(yl.origin.copy(r.object.position),yl.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(yl.direction))s||8*(1-Se.dot(r.object.quaternion))>s||q.distanceToSquared(r.target)>0?(r.dispatchEvent(O_),He.copy(r.object.position),Se.copy(r.object.quaternion),q.copy(r.target),!0):!1}}(),this.dispose=function(){r.domElement.removeEventListener("contextmenu",yt),r.domElement.removeEventListener("pointerdown",N),r.domElement.removeEventListener("pointercancel",ne),r.domElement.removeEventListener("wheel",_e),r.domElement.removeEventListener("pointermove",O),r.domElement.removeEventListener("pointerup",ne),r._domElementKeyEvents!==null&&(r._domElementKeyEvents.removeEventListener("keydown",nt),r._domElementKeyEvents=null)};const r=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let a=i.NONE;const s=1e-6,o=new k_,l=new k_;let u=1;const c=new re,h=new kt,p=new kt,d=new kt,m=new kt,y=new kt,g=new kt,_=new kt,w=new kt,b=new kt,E=new re,T=new kt;let I=!1;const C=[],B={};let R=!1;function k(U){return U!==null?2*Math.PI/60*r.autoRotateSpeed*U:2*Math.PI/60/60*r.autoRotateSpeed}function j(U){const ve=Math.abs(U*.01);return Math.pow(.95,r.zoomSpeed*ve)}function Q(U){l.theta-=U}function ie(U){l.phi-=U}const F=function(){const U=new re;return function(Ze,He){U.setFromMatrixColumn(He,0),U.multiplyScalar(-Ze),c.add(U)}}(),$=function(){const U=new re;return function(Ze,He){r.screenSpacePanning===!0?U.setFromMatrixColumn(He,1):(U.setFromMatrixColumn(He,0),U.crossVectors(r.object.up,U)),U.multiplyScalar(Ze),c.add(U)}}(),L=function(){const U=new re;return function(Ze,He){const Se=r.domElement;if(r.object.isPerspectiveCamera){const q=r.object.position;U.copy(q).sub(r.target);let fe=U.length();fe*=Math.tan(r.object.fov/2*Math.PI/180),F(2*Ze*fe/Se.clientHeight,r.object.matrix),$(2*He*fe/Se.clientHeight,r.object.matrix)}else r.object.isOrthographicCamera?(F(Ze*(r.object.right-r.object.left)/r.object.zoom/Se.clientWidth,r.object.matrix),$(He*(r.object.top-r.object.bottom)/r.object.zoom/Se.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}}();function H(U){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u/=U:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function K(U){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u*=U:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function X(U,ve){if(!r.zoomToCursor)return;I=!0;const Ze=r.domElement.getBoundingClientRect(),He=U-Ze.left,Se=ve-Ze.top,q=Ze.width,fe=Ze.height;T.x=He/q*2-1,T.y=-(Se/fe)*2+1,E.set(T.x,T.y,1).unproject(r.object).sub(r.object.position).normalize()}function J(U){return Math.max(r.minDistance,Math.min(r.maxDistance,U))}function W(U){h.set(U.clientX,U.clientY)}function ae(U){X(U.clientX,U.clientX),_.set(U.clientX,U.clientY)}function Z(U){m.set(U.clientX,U.clientY)}function de(U){p.set(U.clientX,U.clientY),d.subVectors(p,h).multiplyScalar(r.rotateSpeed);const ve=r.domElement;Q(2*Math.PI*d.x/ve.clientHeight),ie(2*Math.PI*d.y/ve.clientHeight),h.copy(p),r.update()}function ye(U){w.set(U.clientX,U.clientY),b.subVectors(w,_),b.y>0?H(j(b.y)):b.y<0&&K(j(b.y)),_.copy(w),r.update()}function Pe(U){y.set(U.clientX,U.clientY),g.subVectors(y,m).multiplyScalar(r.panSpeed),L(g.x,g.y),m.copy(y),r.update()}function ke(U){X(U.clientX,U.clientY),U.deltaY<0?K(j(U.deltaY)):U.deltaY>0&&H(j(U.deltaY)),r.update()}function Be(U){let ve=!1;switch(U.code){case r.keys.UP:U.ctrlKey||U.metaKey||U.shiftKey?ie(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(0,r.keyPanSpeed),ve=!0;break;case r.keys.BOTTOM:U.ctrlKey||U.metaKey||U.shiftKey?ie(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(0,-r.keyPanSpeed),ve=!0;break;case r.keys.LEFT:U.ctrlKey||U.metaKey||U.shiftKey?Q(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(r.keyPanSpeed,0),ve=!0;break;case r.keys.RIGHT:U.ctrlKey||U.metaKey||U.shiftKey?Q(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(-r.keyPanSpeed,0),ve=!0;break}ve&&(U.preventDefault(),r.update())}function et(U){if(C.length===1)h.set(U.pageX,U.pageY);else{const ve=Le(U),Ze=.5*(U.pageX+ve.x),He=.5*(U.pageY+ve.y);h.set(Ze,He)}}function De(U){if(C.length===1)m.set(U.pageX,U.pageY);else{const ve=Le(U),Ze=.5*(U.pageX+ve.x),He=.5*(U.pageY+ve.y);m.set(Ze,He)}}function Xe(U){const ve=Le(U),Ze=U.pageX-ve.x,He=U.pageY-ve.y,Se=Math.sqrt(Ze*Ze+He*He);_.set(0,Se)}function te(U){r.enableZoom&&Xe(U),r.enablePan&&De(U)}function Xt(U){r.enableZoom&&Xe(U),r.enableRotate&&et(U)}function Fe(U){if(C.length==1)p.set(U.pageX,U.pageY);else{const Ze=Le(U),He=.5*(U.pageX+Ze.x),Se=.5*(U.pageY+Ze.y);p.set(He,Se)}d.subVectors(p,h).multiplyScalar(r.rotateSpeed);const ve=r.domElement;Q(2*Math.PI*d.x/ve.clientHeight),ie(2*Math.PI*d.y/ve.clientHeight),h.copy(p)}function ot(U){if(C.length===1)y.set(U.pageX,U.pageY);else{const ve=Le(U),Ze=.5*(U.pageX+ve.x),He=.5*(U.pageY+ve.y);y.set(Ze,He)}g.subVectors(y,m).multiplyScalar(r.panSpeed),L(g.x,g.y),m.copy(y)}function Ve(U){const ve=Le(U),Ze=U.pageX-ve.x,He=U.pageY-ve.y,Se=Math.sqrt(Ze*Ze+He*He);w.set(0,Se),b.set(0,Math.pow(w.y/_.y,r.zoomSpeed)),H(b.y),_.copy(w);const q=(U.pageX+ve.x)*.5,fe=(U.pageY+ve.y)*.5;X(q,fe)}function zt(U){r.enableZoom&&Ve(U),r.enablePan&&ot(U)}function xt(U){r.enableZoom&&Ve(U),r.enableRotate&&Fe(U)}function N(U){r.enabled!==!1&&(C.length===0&&(r.domElement.setPointerCapture(U.pointerId),r.domElement.addEventListener("pointermove",O),r.domElement.addEventListener("pointerup",ne)),vt(U),U.pointerType==="touch"?dt(U):ge(U))}function O(U){r.enabled!==!1&&(U.pointerType==="touch"?be(U):we(U))}function ne(U){ht(U),C.length===0&&(r.domElement.releasePointerCapture(U.pointerId),r.domElement.removeEventListener("pointermove",O),r.domElement.removeEventListener("pointerup",ne)),r.dispatchEvent(D_),a=i.NONE}function ge(U){let ve;switch(U.button){case 0:ve=r.mouseButtons.LEFT;break;case 1:ve=r.mouseButtons.MIDDLE;break;case 2:ve=r.mouseButtons.RIGHT;break;default:ve=-1}switch(ve){case ka.DOLLY:if(r.enableZoom===!1)return;ae(U),a=i.DOLLY;break;case ka.ROTATE:if(U.ctrlKey||U.metaKey||U.shiftKey){if(r.enablePan===!1)return;Z(U),a=i.PAN}else{if(r.enableRotate===!1)return;W(U),a=i.ROTATE}break;case ka.PAN:if(U.ctrlKey||U.metaKey||U.shiftKey){if(r.enableRotate===!1)return;W(U),a=i.ROTATE}else{if(r.enablePan===!1)return;Z(U),a=i.PAN}break;default:a=i.NONE}a!==i.NONE&&r.dispatchEvent(zc)}function we(U){switch(a){case i.ROTATE:if(r.enableRotate===!1)return;de(U);break;case i.DOLLY:if(r.enableZoom===!1)return;ye(U);break;case i.PAN:if(r.enablePan===!1)return;Pe(U);break}}function _e(U){r.enabled===!1||r.enableZoom===!1||a!==i.NONE||(U.preventDefault(),r.dispatchEvent(zc),ke(Ye(U)),r.dispatchEvent(D_))}function Ye(U){const ve=U.deltaMode,Ze={clientX:U.clientX,clientY:U.clientY,deltaY:U.deltaY};switch(ve){case 1:Ze.deltaY*=16;break;case 2:Ze.deltaY*=100;break}return U.ctrlKey&&!R&&(Ze.deltaY*=10),Ze}function Re(U){U.key==="Control"&&(R=!0,document.addEventListener("keyup",We,{passive:!0,capture:!0}))}function We(U){U.key==="Control"&&(R=!1,document.removeEventListener("keyup",We,{passive:!0,capture:!0}))}function nt(U){r.enabled===!1||r.enablePan===!1||Be(U)}function dt(U){switch(Ue(U),C.length){case 1:switch(r.touches.ONE){case Oa.ROTATE:if(r.enableRotate===!1)return;et(U),a=i.TOUCH_ROTATE;break;case Oa.PAN:if(r.enablePan===!1)return;De(U),a=i.TOUCH_PAN;break;default:a=i.NONE}break;case 2:switch(r.touches.TWO){case Oa.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;te(U),a=i.TOUCH_DOLLY_PAN;break;case Oa.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;Xt(U),a=i.TOUCH_DOLLY_ROTATE;break;default:a=i.NONE}break;default:a=i.NONE}a!==i.NONE&&r.dispatchEvent(zc)}function be(U){switch(Ue(U),a){case i.TOUCH_ROTATE:if(r.enableRotate===!1)return;Fe(U),r.update();break;case i.TOUCH_PAN:if(r.enablePan===!1)return;ot(U),r.update();break;case i.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;zt(U),r.update();break;case i.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;xt(U),r.update();break;default:a=i.NONE}}function yt(U){r.enabled!==!1&&U.preventDefault()}function vt(U){C.push(U.pointerId)}function ht(U){delete B[U.pointerId];for(let ve=0;ve{n.preventDefault(),r1(Jz)});eN.addEventListener("change",function(n){const e=n.target.files[0];if(!e)return;const t=new FileReader;t.onload=r=>r1(r.target.result),t.readAsDataURL(e)});let n1;async function r1(n){sa.innerHTML="",ss.textContent="Loading image...";const e=await An.fromURL(n),{canvas:t,setDisplacementMap:r}=rN(n,e.width,e.height);sa.append(t),ss.textContent="Analysing...";const i=performance.now(),{depth:a}=await Qx(e),s=performance.now();ss.textContent=`Done! (Depth estimation took ${Math.round(s-i)}ms)`,r(a.toCanvas());const o=document.createElement("input");o.type="range",o.min=0,o.max=1,o.step=.01,o.addEventListener("input",l=>{n1(parseFloat(l.target.value))}),o.defaultValue=Zx,sa.append(o)}function rN(n,e,t){const r=document.createElement("canvas"),i=r.width=sa.offsetWidth,a=r.height=sa.offsetHeight,s=new Gz,o=new gr(30,i/a,.01,10);o.position.z=2,s.add(o);const l=new Kx({canvas:r,antialias:!0});l.setSize(i,a),l.setPixelRatio(window.devicePixelRatio);const u=new Kz(16777215,2);s.add(u);const c=new Xz().load(n);c.colorSpace=En;const h=new Vz({map:c,side:qr});h.displacementScale=Zx;const p=b=>{h.displacementMap=new Wz(b),h.needsUpdate=!0};n1=b=>{h.displacementScale=b,h.needsUpdate=!0};const[m,y]=e>t?[1,t/e]:[e/t,1],g=new mu(m,y,e,t),_=new hi(g,h);s.add(_);const w=new Qz(o,l.domElement);return w.enableDamping=!0,l.setAnimationLoop(()=>{l.render(s,o),w.update()}),window.addEventListener("resize",()=>{const b=sa.offsetWidth,E=sa.offsetHeight;o.aspect=b/E,o.updateProjectionMatrix(),l.setSize(b,E)},!1),{canvas:l.domElement,setDisplacementMap:p}}