diff --git "a/dist/assets/index-WzmSvmGf.js" "b/dist/assets/index-WzmSvmGf.js" new file mode 100644--- /dev/null +++ "b/dist/assets/index-WzmSvmGf.js" @@ -0,0 +1,4004 @@ +var e=Object.defineProperty,t=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},r=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var i=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=i()})),o=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),s=t(((e,t)=>{t.exports=o()})),c=t((e=>{var t=a();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=c()})),u=t((e=>{var t=s(),n=a(),r=l();function i(e){var t=`https://react.dev/errors/`+e;if(1I||(e.current=re[I],re[I]=null,I--)}function oe(e,t){I++,re[I]=e.current,e.current=t}var se=ie(null),ce=ie(null),le=ie(null),ue=ie(null);function de(e,t){switch(oe(le,t),oe(ce,e),oe(se,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Kd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Kd(t),e=qd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ae(se),oe(se,e)}function fe(){ae(se),ae(ce),ae(le)}function pe(e){e.memoizedState!==null&&oe(ue,e);var t=se.current,n=qd(t,e.type);t!==n&&(oe(ce,e),oe(se,n))}function me(e){ce.current===e&&(ae(se),ae(ce)),ue.current===e&&(ae(ue),rp._currentValue=ne)}var L,he;function R(e){if(L===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);L=t&&t[1]||``,he=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{ge=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?R(n):``}function ve(e,t){switch(e.tag){case 26:case 27:case 5:return R(e.type);case 16:return R(`Lazy`);case 13:return e.child!==t&&t!==null?R(`Suspense Fallback`):R(`Suspense`);case 19:return R(`SuspenseList`);case 0:case 15:return _e(e.type,!1);case 11:return _e(e.type.render,!1);case 1:return _e(e.type,!0);case 31:return R(`Activity`);default:return``}}function ye(e){try{var t=``,n=null;do t+=ve(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var be=Object.prototype.hasOwnProperty,xe=t.unstable_scheduleCallback,Se=t.unstable_cancelCallback,Ce=t.unstable_shouldYield,we=t.unstable_requestPaint,Te=t.unstable_now,Ee=t.unstable_getCurrentPriorityLevel,De=t.unstable_ImmediatePriority,Oe=t.unstable_UserBlockingPriority,ke=t.unstable_NormalPriority,Ae=t.unstable_LowPriority,je=t.unstable_IdlePriority,Me=t.log,Ne=t.unstable_setDisableYieldValue,Pe=null,z=null;function Fe(e){if(typeof Me==`function`&&Ne(e),z&&typeof z.setStrictMode==`function`)try{z.setStrictMode(Pe,e)}catch{}}var Ie=Math.clz32?Math.clz32:ze,Le=Math.log,Re=Math.LN2;function ze(e){return e>>>=0,e===0?32:31-(Le(e)/Re|0)|0}var Be=256,Ve=262144,He=4194304;function Ue(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function We(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Ue(n))):i=Ue(o):i=Ue(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ue(n))):i=Ue(o)):i=Ue(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Ge(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ke(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function qe(){var e=He;return He<<=1,!(He&62914560)&&(He=4194304),e}function Je(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ye(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Xe(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),ln=!1;if(cn)try{var un={};Object.defineProperty(un,`passive`,{get:function(){ln=!0}}),window.addEventListener(`test`,un,un),window.removeEventListener(`test`,un,un)}catch{ln=!1}var dn=null,fn=null,pn=null;function mn(){if(pn)return pn;var e,t=fn,n=t.length,r,i=`value`in dn?dn.value:dn.textContent,a=i.length;for(e=0;e=Kn),Yn=` `,Xn=!1;function Zn(e,t){switch(e){case`keyup`:return Wn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Qn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var $n=!1;function er(e,t){switch(e){case`compositionend`:return Qn(t);case`keypress`:return t.which===32?(Xn=!0,Yn):null;case`textInput`:return e=t.data,e===Yn&&Xn?null:e;default:return null}}function tr(e,t){if($n)return e===`compositionend`||!Gn&&Zn(e,t)?(e=mn(),pn=fn=dn=null,$n=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Sr(n)}}function wr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?wr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Tr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Ft(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ft(e.document)}return t}function Er(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Dr=cn&&`documentMode`in document&&11>=document.documentMode,Or=null,kr=null,Ar=null,jr=!1;function Mr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;jr||Or==null||Or!==Ft(r)||(r=Or,`selectionStart`in r&&Er(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ar&&xr(Ar,r)||(Ar=r,r=Ad(kr,`onSelect`),0>=o,i-=o,Ci=1<<32-Ie(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Mi&&Ti(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Mi&&Ti(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Mi&&Ti(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Mi&&Ti(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&wa(l)===r.type){n(e,r.sibling),c=a(r,o.props),ja(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===y?(c=di(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=ui(o.type,o.key,o.props,null,e.mode,c),ja(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=mi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=wa(o),b(e,r,o,c)}if(te(o))return h(e,r,o,c);if(M(o)){if(l=M(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Aa(o),c);if(o.$$typeof===C)return b(e,r,H(e,o),c);Ma(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=fi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{ka=0;var i=b(e,t,n,r);return Oa=null,i}catch(t){if(t===va||t===ba)throw t;var a=oi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Pa=Na(!0),Fa=Na(!1),Ia=!1;function La(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ra(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function za(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ba(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ll&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ri(e),ni(e,null,n),t}return $r(e,r,t,n),ri(e)}function Va(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}function Ha(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Ua=!1;function Wa(){if(Ua){var e=la;if(e!==null)throw e}}function Ga(e,t,n,r){Ua=!1;var i=e.updateQueue;Ia=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Bl&f)===f:(r&f)===f){f!==0&&f===ca&&(Ua=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Ia=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),ql|=o,e.lanes=o,e.memoizedState=d}}function Ka(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function qa(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=P.T,s={};P.T=s,js(e,!1,t,n);try{var c=i(),l=P.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?As(e,t,fa(c,r),hu(e)):As(e,t,r,hu(e))}catch(n){As(e,t,{then:function(){},status:`rejected`,reason:n},hu())}finally{F.p=a,o!==null&&s.types!==null&&(o.types=s.types),P.T=o}}function bs(){}function xs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ss(e).queue;ys(e,a,t,ne,n===null?bs:function(){return Cs(e),n(r)})}function Ss(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ne,baseState:ne,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:ne},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Cs(e){var t=Ss(e);t.next===null&&(t=e.alternate.memoizedState),As(e,t.next.queue,{},hu())}function ws(){return $i(rp)}function Ts(){return ko().memoizedState}function Es(){return ko().memoizedState}function Ds(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=hu();e=za(n);var r=Ba(t,e,n);r!==null&&(_u(r,t,n),Va(r,t,n)),t={cache:ia()},e.payload=t;return}t=t.return}}function Os(e,t,n){var r=hu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ms(e)?Ns(t,n):(n=ei(e,t,n,r),n!==null&&(_u(n,e,r),Ps(n,t,r)))}function ks(e,t,n){As(e,t,n,hu())}function As(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ms(e))Ns(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,br(s,o))return $r(e,t,i,0),Rl===null&&Qr(),!1}catch{}if(n=ei(e,t,i,r),n!==null)return _u(n,e,r),Ps(n,t,r),!0}return!1}function js(e,t,n,r){if(r={lane:2,revertLane:md(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ms(e)){if(t)throw Error(i(479))}else t=ei(e,n,r,2),t!==null&&_u(t,e,2)}function Ms(e){var t=e.alternate;return e===co||t!==null&&t===co}function Ns(e,t){po=fo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ps(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}var Fs={readContext:$i,use:Mo,useCallback:yo,useContext:yo,useEffect:yo,useImperativeHandle:yo,useLayoutEffect:yo,useInsertionEffect:yo,useMemo:yo,useReducer:yo,useRef:yo,useState:yo,useDebugValue:yo,useDeferredValue:yo,useTransition:yo,useSyncExternalStore:yo,useId:yo,useHostTransitionStatus:yo,useFormState:yo,useActionState:yo,useOptimistic:yo,useMemoCache:yo,useCacheRefresh:yo};Fs.useEffectEvent=yo;var Is={readContext:$i,use:Mo,useCallback:function(e,t){return Oo().memoizedState=[e,t===void 0?null:t],e},useContext:$i,useEffect:os,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),is(4194308,4,fs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return is(4194308,4,e,t)},useInsertionEffect:function(e,t){is(4,2,e,t)},useMemo:function(e,t){var n=Oo();t=t===void 0?null:t;var r=e();if(mo){Fe(!0);try{e()}finally{Fe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Oo();if(n!==void 0){var i=n(t);if(mo){Fe(!0);try{n(t)}finally{Fe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Os.bind(null,co,e),[r.memoizedState,e]},useRef:function(e){var t=Oo();return e={current:e},t.memoizedState=e},useState:function(e){e=Wo(e);var t=e.queue,n=ks.bind(null,co,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ms,useDeferredValue:function(e,t){return _s(Oo(),e,t)},useTransition:function(){var e=Wo(!1);return e=ys.bind(null,co,e.queue,!0,!1),Oo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=co,a=Oo();if(Mi){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Rl===null)throw Error(i(349));Bl&127||zo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,os(Vo.bind(null,r,o,e),[e]),r.flags|=2048,ns(9,{destroy:void 0},Bo.bind(null,r,o,n,t),null),n},useId:function(){var e=Oo(),t=Rl.identifierPrefix;if(Mi){var n=wi,r=Ci;n=(r&~(1<<32-Ie(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=ho++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[at]=t,o[ot]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(zd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Ac(t)}}return Fc(t),jc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Ac(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=le.current,zi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Ai,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[at]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Id(e.nodeValue,n)),e||Ii(t,!0)}else e=Gd(e).createTextNode(r),e[at]=t,t.stateNode=e}return Fc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=zi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[at]=t}else Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),e=!1}else n=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(io(t),t):(io(t),null);if(t.flags&128)throw Error(i(558))}return Fc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=zi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[at]=t}else Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),a=!1}else a=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(io(t),t):(io(t),null)}return io(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Nc(t,t.updateQueue),Fc(t),null);case 4:return fe(),e===null&&Ed(t.stateNode.containerInfo),Fc(t),null;case 10:return qi(t.type),Fc(t),null;case 19:if(ae(ao),r=t.memoizedState,r===null)return Fc(t),null;if(a=(t.flags&128)!=0,o=r.rendering,o===null)if(a)Pc(r,!1);else{if(Kl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=oo(e),o!==null){for(t.flags|=128,Pc(r,!1),e=o.updateQueue,t.updateQueue=e,Nc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)li(n,e),n=n.sibling;return oe(ao,ao.current&1|2),Mi&&Ti(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Te()>ru&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304)}else{if(!a)if(e=oo(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Nc(t,e),Pc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Mi)return Fc(t),null}else 2*Te()-r.renderingStartTime>ru&&n!==536870912&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Fc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Te(),e.sibling=null,n=ao.current,oe(ao,a?n&1|2:n&1),Mi&&Ti(t,r.treeForkCount),e);case 22:case 23:return io(t),W(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Fc(t),t.subtreeFlags&6&&(t.flags|=8192)):Fc(t),n=t.updateQueue,n!==null&&Nc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&ae(ma),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),qi(ra),Fc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Lc(e,t){switch(Oi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return qi(ra),fe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return me(t),null;case 31:if(t.memoizedState!==null){if(io(t),t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(io(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ae(ao),null;case 4:return fe(),null;case 10:return qi(t.type),null;case 22:case 23:return io(t),W(),e!==null&&ae(ma),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return qi(ra),null;case 25:return null;default:return null}}function Rc(e,t){switch(Oi(t),t.tag){case 3:qi(ra),fe();break;case 26:case 27:case 5:me(t);break;case 4:fe();break;case 31:t.memoizedState!==null&&io(t);break;case 13:io(t);break;case 19:ae(ao);break;case 10:qi(t.type);break;case 22:case 23:io(t),W(),e!==null&&ae(ma);break;case 24:qi(ra)}}function zc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){qu(t,t.return,e)}}function Bc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){qu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){qu(t,t.return,e)}}function Vc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{qa(t,n)}catch(t){qu(e,e.return,t)}}}function Hc(e,t,n){n.props=Us(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){qu(e,t,n)}}function Uc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){qu(e,t,n)}}function Wc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){qu(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){qu(e,t,n)}else n.current=null}function Gc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){qu(e,e.return,t)}}function Kc(e,t,n){try{var r=e.stateNode;Bd(r,e.type,n,t),r[ot]=t}catch(t){qu(e,e.return,t)}}function qc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&nf(e.type)||e.tag===4}function Jc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||qc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&nf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Yc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Qt));else if(r!==4&&(r===27&&nf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Yc(e,t,n),e=e.sibling;e!==null;)Yc(e,t,n),e=e.sibling}function Xc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&nf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Xc(e,t,n),e=e.sibling;e!==null;)Xc(e,t,n),e=e.sibling}function Zc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);zd(t,r,n),t[at]=e,t[ot]=n}catch(t){qu(e,e.return,t)}}var Qc=!1,$c=!1,el=!1,tl=typeof WeakSet==`function`?WeakSet:Set,nl=null;function rl(e,t){if(e=e.containerInfo,Ud=fp,e=Tr(e),Er(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Wd={focusedElem:e,selectionRange:n},fp=!1,nl=t;nl!==null;)if(t=nl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,nl=e;else for(;nl!==null;){switch(t=nl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),zd(o,r,n),o[at]=e,vt(o),r=o;break a;case`link`:var s=Kf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Cr(s,h),v=Cr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,P.T=null,n=du,du=null;var o=su,s=lu;if(ou=0,cu=su=null,lu=0,Ll&6)throw Error(i(331));var c=Ll;if(Ll|=4,Ml(o.current),wl(o,o.current,s,n),Ll=c,sd(0,!1),z&&typeof z.onPostCommitFiberRoot==`function`)try{z.onPostCommitFiberRoot(Pe,o)}catch{}return!0}finally{F.p=a,P.T=r,Uu(e,t)}}function Ku(e,t,n){t=gi(n,t),t=Ys(e.stateNode,t,2),e=Ba(e,t,2),e!==null&&(Ye(e,2),od(e))}function qu(e,t,n){if(e.tag===3)Ku(e,e,n);else for(;t!==null;){if(t.tag===3){Ku(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(au===null||!au.has(r))){e=gi(n,e),n=Xs(2),r=Ba(t,n,2),r!==null&&(Zs(n,r,t,e),Ye(r,2),od(r));break}}t=t.return}}function Ju(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Il;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Gl=!0,i.add(n),e=Yu.bind(null,e,t,n),t.then(e,e))}function Yu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Rl===e&&(Bl&n)===n&&(Kl===4||Kl===3&&(Bl&62914560)===Bl&&300>Te()-tu?!(Ll&2)&&wu(e,0):Yl|=n,Zl===Bl&&(Zl=0)),od(e)}function Xu(e,t){t===0&&(t=qe()),e=ti(e,t),e!==null&&(Ye(e,t),od(e))}function Zu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Xu(e,n)}function Qu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Xu(e,n)}function $u(e,t){return xe(e,t)}var ed=null,td=null,nd=!1,rd=!1,id=!1,ad=0;function od(e){e!==td&&e.next===null&&(td===null?ed=td=e:td=td.next=e),rd=!0,nd||(nd=!0,pd())}function sd(e,t){if(!id&&rd){id=!0;do for(var n=!1,r=ed;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Ie(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,fd(r,a))}else a=Bl,a=We(r,r===Rl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ge(r,a)||(n=!0,fd(r,a));r=r.next}while(n);id=!1}}function cd(){ld()}function ld(){rd=nd=!1;var e=0;ad!==0&&Xd()&&(e=ad);for(var t=Te(),n=null,r=ed;r!==null;){var i=r.next,a=ud(r,t);a===0?(r.next=null,n===null?ed=i:n.next=i,i===null&&(td=n)):(n=r,(e!==0||a&3)&&(rd=!0)),r=i}ou!==0&&ou!==5||sd(e,!1),ad!==0&&(ad=0)}function ud(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Vd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Ef(e,t,n){var r=Tf;if(r&&typeof t==`string`&&t){var i=Lt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),bf.has(i)||(bf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),zd(t,`link`,e),vt(t),r.head.appendChild(t)))}}function Df(e){Sf.D(e),Ef(`dns-prefetch`,e,null)}function Of(e,t){Sf.C(e,t),Ef(`preconnect`,e,t)}function kf(e,t,n){Sf.L(e,t,n);var r=Tf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Lt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Lt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Lt(n.imageSizes)+`"]`)):i+=`[href="`+Lt(e)+`"]`;var a=i;switch(t){case`style`:a=Ff(e);break;case`script`:a=zf(e)}yf.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),yf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(If(a))||t===`script`&&r.querySelector(Bf(a))||(t=r.createElement(`link`),zd(t,`link`,e),vt(t),r.head.appendChild(t)))}}function Af(e,t){Sf.m(e,t);var n=Tf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Lt(r)+`"][href="`+Lt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=zf(e)}if(!yf.has(a)&&(e=h({rel:`modulepreload`,href:e},t),yf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Bf(a)))return}r=n.createElement(`link`),zd(r,`link`,e),vt(r),n.head.appendChild(r)}}}function jf(e,t,n){Sf.S(e,t,n);var r=Tf;if(r&&e){var i=_t(r).hoistableStyles,a=Ff(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(If(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=yf.get(a))&&Uf(e,n);var c=o=r.createElement(`link`);vt(c),zd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Hf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Mf(e,t){Sf.X(e,t);var n=Tf;if(n&&e){var r=_t(n).hoistableScripts,i=zf(e),a=r.get(i);a||(a=n.querySelector(Bf(i)),a||(e=h({src:e,async:!0},t),(t=yf.get(i))&&Wf(e,t),a=n.createElement(`script`),vt(a),zd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nf(e,t){Sf.M(e,t);var n=Tf;if(n&&e){var r=_t(n).hoistableScripts,i=zf(e),a=r.get(i);a||(a=n.querySelector(Bf(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=yf.get(i))&&Wf(e,t),a=n.createElement(`script`),vt(a),zd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Pf(e,t,n,r){var a=(a=le.current)?xf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Ff(n.href),n=_t(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Ff(n.href);var o=_t(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(If(e)))&&!o._p&&(s.instance=o,s.state.loading=5),yf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},yf.set(e,n),o||Rf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=zf(n),n=_t(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Ff(e){return`href="`+Lt(e)+`"`}function If(e){return`link[rel="stylesheet"][`+e+`]`}function Lf(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function Rf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),zd(t,`link`,n),vt(t),e.head.appendChild(t))}function zf(e){return`[src="`+Lt(e)+`"]`}function Bf(e){return`script[async]`+e}function Vf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Lt(n.href)+`"]`);if(r)return t.instance=r,vt(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),vt(r),zd(r,`style`,a),Hf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Ff(n.href);var o=e.querySelector(If(a));if(o)return t.state.loading|=4,t.instance=o,vt(o),o;r=Lf(n),(a=yf.get(a))&&Uf(r,a),o=(e.ownerDocument||e).createElement(`link`),vt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),zd(o,`link`,r),t.state.loading|=4,Hf(o,n.precedence,e),t.instance=o;case`script`:return o=zf(n.src),(a=e.querySelector(Bf(o)))?(t.instance=a,vt(a),a):(r=n,(a=yf.get(o))&&(r=h({},n),Wf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),vt(a),zd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Hf(r,n.precedence,e));return t.instance}function Hf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Jf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Yf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Xf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Ff(r.href),a=t.querySelector(If(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=$f.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,vt(a);return}a=t.ownerDocument||t,r=Lf(r),(i=yf.get(i))&&Uf(r,i),a=a.createElement(`link`),vt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),zd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=$f.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Zf=0;function Qf(e,t){return e.stylesheets&&e.count===0&&tp(e,e.stylesheets),0Zf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function $f(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)tp(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var ep=null;function tp(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,ep=new Map,t.forEach(np,e),ep=null,$f.call(e))}function np(e,t){if(!(t.state.loading&4)){var n=ep.get(e);if(n)var r=n.get(null);else{n=new Map,ep.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=u()})),f=a(),p=d(),m=`modulepreload`,h=function(e){return`/`+e},g={},_=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=h(t,n),t in g)return;g[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:m,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},v=n({InferenceSession:()=>Pe,TRACE:()=>Te,TRACE_EVENT_BEGIN:()=>ke,TRACE_EVENT_END:()=>Ae,TRACE_FUNC_BEGIN:()=>De,TRACE_FUNC_END:()=>Oe,Tensor:()=>Ce,default:()=>B,env:()=>I,registerBackend:()=>A}),y=Object.defineProperty,b=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyNames,S=Object.prototype.hasOwnProperty,C=(e=>typeof r<`u`?r:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof r<`u`?r:e)[t]}):e)(function(e){if(typeof r<`u`)return r.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),w=(e,t)=>()=>(e&&(t=e(e=0)),t),T=(e,t)=>{for(var n in t)y(e,n,{get:t[n],enumerable:!0})},E=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of x(t))!S.call(e,i)&&i!==n&&y(e,i,{get:()=>t[i],enumerable:!(r=b(t,i))||r.enumerable});return e},D=e=>E(y({},`__esModule`,{value:!0}),e),O,k,A,j,M,N=w(()=>{O=new Map,k=[],A=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=O.get(e);if(r===void 0)O.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=k.indexOf(e);t!==-1&&k.splice(t,1);for(let t=0;t{let t=O.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},M=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?k:n,i,a=[],o=new Set;for(let e of r){let t=await j(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),ee=w(()=>{N()}),te,P=w(()=>{te=`1.24.0-dev.20251116-b39e144322`}),F,ne,re=w(()=>{P(),F=`warning`,ne={wasm:{},webgl:{},webgpu:{},versions:{common:te},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);F=e}},get logLevel(){return F}},Object.defineProperty(ne,`logLevel`,{enumerable:!0})}),I,ie=w(()=>{re(),I=ne}),ae,oe,se=w(()=>{ae=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{Se(),ce=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,ce(o,s)}else throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(ce(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return ce(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},ue=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new xe({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},de=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new xe({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},fe=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new xe({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},pe=(e,t,n)=>new xe({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),L,he,R,ge,_e=w(()=>{L=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),he=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),R=!1,ge=()=>{if(!R){R=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(L.set(`int64`,BigInt64Array),he.set(BigInt64Array,`int64`)),t&&(L.set(`uint64`,BigUint64Array),he.set(BigUint64Array,`uint64`)),r?(L.set(`float16`,n),he.set(n,`float16`)):L.set(`float16`,Uint16Array)}}}),ve,ye,be=w(()=>{Se(),ve=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new xe(e.type,e.data,t);case`cpu-pinned`:return new xe({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new xe({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new xe({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new xe({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),xe,Se=w(()=>{se(),me(),_e(),be(),xe=class{constructor(e,t,n){ge();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=L.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=L.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=he.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=ve(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw 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(e,t){return le(e,t)}static fromTexture(e,t){return ue(e,t)}static fromGpuBuffer(e,t){return de(e,t)}static fromMLTensor(e,t){return fe(e,t)}static fromPinnedBuffer(e,t,n){return pe(e,t,n)}toDataURL(e){return ae(this,e)}toImageData(e){return oe(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let 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 Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ye(this,e)}}}),Ce,we=w(()=>{Se(),Ce=xe}),Te,Ee,De,Oe,ke,Ae,je=w(()=>{re(),Te=(e,t)=>{(typeof ne.trace>`u`?!ne.wasm.trace:!ne.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ee=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof ne.trace>`u`?!ne.wasm.trace:!ne.trace)||Ee(`BEGIN`,e)},Oe=e=>{(typeof ne.trace>`u`?!ne.wasm.trace:!ne.trace)||Ee(`END`,e)},ke=e=>{(typeof ne.trace>`u`?!ne.wasm.trace:!ne.trace)||console.time(`ORT::${e}`)},Ae=e=>{(typeof ne.trace>`u`?!ne.wasm.trace:!ne.trace)||console.timeEnd(`ORT::${e}`)}}),Me,Ne=w(()=>{N(),we(),je(),Me=class e{constructor(e){this.handler=e}async run(e,t,n){De(),ke(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof Ce||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof Ce)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof Ce)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];t instanceof Ce?s[e]=t:s[e]=new Ce(t.type,t.data,t.dims)}return Ae(`InferenceSession.run`),Oe(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){De(),ke(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await M(o),l=await s.createInferenceSessionHandler(a,c);return Ae(`InferenceSession.create`),Oe(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Pe,z=w(()=>{Ne(),Pe=Me}),Fe=w(()=>{}),Ie=w(()=>{}),Le=w(()=>{}),Re=w(()=>{}),ze={};T(ze,{InferenceSession:()=>Pe,TRACE:()=>Te,TRACE_EVENT_BEGIN:()=>ke,TRACE_EVENT_END:()=>Ae,TRACE_FUNC_BEGIN:()=>De,TRACE_FUNC_END:()=>Oe,Tensor:()=>Ce,env:()=>I,registerBackend:()=>A});var Be=w(()=>{ee(),ie(),z(),we(),Fe(),Ie(),je(),Le(),Re()}),Ve=w(()=>{}),He={};T(He,{default:()=>Ge});var Ue,We,Ge,Ke=w(()=>{Fn(),St(),ft(),Ue=`ort-wasm-proxy-worker`,We=globalThis.self?.name===Ue,We&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:bt(n.wasm).then(()=>{Cn(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;wn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=On(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;kn(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:An(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Mn(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Pn([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Nn(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),Ge=We?null:e=>new Worker(e??tt,{type:`module`,name:Ue})}),qe={};T(qe,{default:()=>Ye});async function Je(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.Uc||=new Map).set(e,n)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=$t;return t=e(...t),$t==n?t:new Promise((e,t)=>{sn={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=import.meta.url,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(S(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,x=!1,S=e=>e.startsWith(`file://`);function C(){Se.buffer!=T.buffer&&F()}if(i){let e=function(n){try{var r=n.data,i=r.Oc;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({Oc:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.ce)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({Oc:`callHandler`,be:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));Se=r.ie,F(),f=r.je,ie(),Ao()}else if(i===`run`){(function(e){var t=(C(),A)[e+52>>>2>>>0];e=(C(),A)[e+56>>>2>>>0],$i(t,t-e),H(t)})(r.Nc),Ui(r.Nc,0,0,1,0,0),ye(),Ht(r.Nc),w||=(bi(),!0);try{Ce(r.ge,r.Wc)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?w&&Ut():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw Wi(),e}};var w=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var T,E,D,O,k,A,j,M,N,ee,te,P=!1;function F(){var e=Se.buffer;t.HEAP8=T=new Int8Array(e),D=new Int16Array(e),t.HEAPU8=E=new Uint8Array(e),O=new Uint16Array(e),t.HEAP32=k=new Int32Array(e),t.HEAPU32=A=new Uint32Array(e),j=new Float32Array(e),M=new Float64Array(e),N=new BigInt64Array(e),ee=new BigUint64Array(e)}function ne(){P=!0,i?g():Ga._b()}function re(e){throw b(e=`Aborted(`+e+`)`),x=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function I(){return{a:{f:De,J:ke,k:Pe,p:z,l:Fe,sa:Ie,b:Le,ca:Re,Ja:Be,q:Ve,da:Ke,Za:qe,Fa:Je,Ha:Ye,_a:Xe,Xa:Ze,Qa:Qe,Wa:$e,oa:et,Ga:tt,Xb:nt,Ya:rt,Yb:it,db:at,Da:pt,Sb:mt,Qb:St,Ca:wt,M:Tt,I:Et,Rb:kt,ja:Lt,Tb:Rt,Ta:zt,Vb:Wt,Ka:Kt,Ob:qt,ka:Jt,Sa:Ht,ab:Yt,U:un,n:_n,c:_t,rb:vn,w:yn,L:bn,z:xn,j:Sn,o:Cn,sb:wn,G:Tn,T:En,h:Dn,u:On,m:kn,i:An,Na:jn,Oa:Fn,Pa:In,La:Ln,Ma:Rn,Pb:Vn,eb:Hn,cb:Gn,Y:Jn,qb:Yn,la:Xn,bb:Un,fb:Zn,$a:Qn,Wb:$n,N:Bn,gb:er,X:tr,Ub:nr,nb:Cr,C:wr,ra:Tr,qa:Er,pb:Dr,W:Or,v:kr,mb:Ar,lb:jr,kb:Mr,ob:Nr,jb:Pr,ib:Fr,hb:Ir,Ua:Br,Va:Vr,Ia:L,V:Hr,na:Ur,Ra:Wr,ma:Kr,Cb:Oo,xa:So,Db:Do,ya:xo,F:lo,e:Za,s:Ya,x:Ja,B:oo,Fb:vo,ba:_o,D:$a,za:yo,$:Co,ga:go,Gb:ho,Hb:mo,Ba:uo,Aa:po,Ib:fo,wa:Eo,aa:bo,d:Xa,A:Qa,r:W,Bb:ko,t:to,y:so,H:eo,E:no,K:co,R:wo,ia:ao,_:To,Jb:io,Kb:ro,g:qr,a:Se,Nb:pe,Eb:Jr,ha:Yr,O:Xr,pa:Zr,Lb:Qr,ta:$r,Q:ei,yb:ti,zb:ni,ua:ri,ea:ii,P:ai,Ea:oi,va:si,Z:ci,wb:li,Zb:ui,S:di,Ab:fi,tb:pi,ub:hi,vb:gi,fa:_i,xb:vi,Mb:yi}}}async function ie(){function e(e,n){var r=Ga=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=Zt(n),e[t]=r):e[t]=n;return Ga=e,Ga=function(){var e=Ga,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).$b=t(e.$b),e.Cc=n(e.Cc),e.Ec=t(e.Ec),e.rd=(e=>(t,n)=>e(t,n)>>>0)(e.rd),e.wd=t(e.wd),e.xd=n(e.xd),e.Bd=t(e.Bd),e}(),ge.push(Ga.id),V=(e=Ga).$b,bi=e.ac,t._OrtInit=e.bc,t._OrtGetLastError=e.cc,t._OrtCreateSessionOptions=e.dc,t._OrtAppendExecutionProvider=e.ec,t._OrtAddFreeDimensionOverride=e.fc,t._OrtAddSessionConfigEntry=e.gc,t._OrtReleaseSessionOptions=e.hc,t._OrtCreateSession=e.ic,t._OrtReleaseSession=e.jc,t._OrtGetInputOutputCount=e.kc,t._OrtGetInputOutputMetadata=e.lc,t._OrtFree=e.mc,t._OrtCreateTensor=e.nc,t._OrtGetTensorData=e.oc,t._OrtReleaseTensor=e.pc,t._OrtCreateRunOptions=e.qc,t._OrtAddRunConfigEntry=e.rc,t._OrtReleaseRunOptions=e.sc,t._OrtCreateBinding=e.tc,t._OrtBindInput=e.uc,t._OrtBindOutput=e.vc,t._OrtClearBoundOutputs=e.wc,t._OrtReleaseBinding=e.xc,t._OrtRunWithBinding=e.yc,t._OrtRun=e.zc,t._OrtEndProfiling=e.Ac,xi=t._OrtGetWebGpuDevice=e.Bc,Si=e.Cc,Ci=t._free=e.Dc,wi=t._malloc=e.Ec,Ti=t._wgpuBufferRelease=e.Fc,Ei=t._wgpuCreateInstance=e.Gc,Di=e.Hc,Oi=e.Ic,ki=e.Jc,Ai=e.Kc,ji=e.Lc,Mi=e.Pc,Ni=e.Zc,Pi=e._c,Fi=e.$c,Ii=e.bd,Li=e.cd,Ri=e.dd,zi=e.ed,Bi=e.fd,Vi=e.gd,Hi=e.hd,Ui=e.kd,Wi=e.ld,Gi=e.md,Ki=e.nd,qi=e.od,Ji=e.pd,Yi=e.qd,Xi=e.rd,Zi=e.sd,Qi=e.td,$i=e.ud,H=e.vd,ea=e.wd,U=e.xd,ta=e.yd,na=e.zd,ra=e.Ad,ia=e.Bd,aa=e.Cd,oa=e.Dd,sa=e.Ed,ca=e.Fd,la=e.Gd,ua=e.Hd,da=e.Id,fa=e.Jd,pa=e.Kd,ma=e.Ld,ha=e.Md,ga=e.Nd,_a=e.Od,va=e.Pd,ya=e.Qd,ba=e.Rd,xa=e.Td,Sa=e.Ud,Ca=e.Vd,wa=e.Wd,Ta=e.Yd,Ea=e.Zd,Da=e._d,Oa=e.$d,ka=e.ae,Aa=e.oe,ja=e.pe,Ma=e.qe,Na=e.re,Pa=e.se,Fa=e.te,Ia=e.ue,La=e.ve,Ra=e.we,za=e.xe,Ba=e.ye,Va=e.Ye,Ha=e.Ze,Ua=e._e,Wa=e.$e,f=n,Ga}var n,r=I();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,I()),f):(te??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(`/assets/ort-wasm-simd-threaded.asyncify-CtKKja6V.wasm`,``+import.meta.url).href,n=await async function(e){var t=te;if(!d&&!S(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return async function(e,t){try{var n=await async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==te&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e}(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),re(e)}}(t,e)}(r),e(n.instance,n.module))}class ae{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var oe=e=>{e.terminate(),e.onmessage=()=>{}},se=[],ce=0,le=null,ue=e=>{he.length==0&&(xe(),be(he[0]));var t=he.pop();if(!t)return 6;R.push(t),_e[e.Nc]=t,t.Nc=e.Nc;var n={Oc:`run`,ge:e.fe,Wc:e.Wc,Nc:e.Nc};return t.postMessage(n,e.Yc),0},de=0,fe=(e,t,...n)=>{var r,i=16*n.length,a=U(),o=ea(i),s=o>>>3;for(r of n)typeof r==`bigint`?((C(),N)[s++>>>0]=1n,(C(),N)[s++>>>0]=r):((C(),N)[s++>>>0]=0n,(C(),M)[s++>>>0]=r);return e=Gi(e,0,i,o,t),H(a),e};function pe(e){if(i)return fe(0,1,e);if(p=e,!(0{if(p=e,i)throw me(e),`unwind`;pe(e)},he=[],R=[],ge=[],_e={},ve=e=>{var t=e.Nc;delete _e[t],he.push(e),R.splice(R.indexOf(e),1),e.Nc=0,Ki(t)};function ye(){ge.forEach(e=>e())}var be=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.Oc,i.Vc&&i.Vc!=Si()){var a=_e[i.Vc];a?a.postMessage(i,i.Yc):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.Vc}, but that thread no longer exists!`)}else r===`checkMailbox`?Ut():r===`spawnThread`?ue(i):r===`cleanupThread`?Bt(()=>{ve(_e[i.he])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.be](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({Oc:`load`,ce:i,ie:Se,je:f})});function xe(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.webgpu.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});he.push(e)}var Se,Ce=(e,t)=>{de=0,e=oa(e,t),0-9007199254740992>e||9007199254740992>>=0);return(C(),T)[t.Qc+12>>>0]==0&&(Ae(t,!0),Te--),je(t,!1),we.push(t),ia(e)}var Oe=0,ke=()=>{Zi(0,0);var e=we.pop();ta(e.Xc),Oe=0};function Ae(e,t){t=+!!t,(C(),T)[e.Qc+12>>>0]=t}function je(e,t){t=+!!t,(C(),T)[e.Qc+13>>>0]=t}class Me{constructor(e){this.Xc=e,this.Qc=e-24}}var Ne=e=>{var t=Oe;if(!t)return Qi(0),0;var n=new Me(t);(C(),A)[n.Qc+16>>>2>>>0]=t;var r=(C(),A)[n.Qc+4>>>2>>>0];if(!r)return Qi(0),t;for(var i of e){if(i===0||i===r)break;if(ra(i,r,n.Qc+16))return Qi(i),t}return Qi(r),t};function Pe(){return Ne([])}function z(e){return Ne([e>>>0])}function Fe(e,t,n,r){return Ne([e>>>0,t>>>0,n>>>0,r>>>0])}var Ie=()=>{var e=we.pop();e||re(`no exception to throw`);var t=e.Xc;throw(C(),T)[e.Qc+13>>>0]==0&&(we.push(e),je(e,!0),Ae(e,!1),Te++),na(t),Oe=t};function Le(e,t,n){var r=new Me(e>>>=0);throw t>>>=0,n>>>=0,(C(),A)[r.Qc+16>>>2>>>0]=0,(C(),A)[r.Qc+4>>>2>>>0]=t,(C(),A)[r.Qc+8>>>2>>>0]=n,na(e),Te++,Oe=e}var Re=()=>Te;function ze(e,t,n,r){return i?fe(2,1,e,t,n,r):Be(e,t,n,r)}function Be(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?ze(e,t,n,r):(e={fe:n,Nc:e,Wc:r,Yc:a},i?(e.Oc=`spawnThread`,postMessage(e,a),0):ue(e))}function Ve(e){throw Oe||=e>>>0,Oe}var He=globalThis.TextDecoder&&new TextDecoder,Ue=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},We=(e,t=0,n,r)=>{if(16<(n=Ue(e,t>>>=0,n,r))-t&&e.buffer&&He)return He.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},Ge=(e,t,n)=>(e>>>=0)?We((C(),E),e,t,n):``;function Ke(e,t,n){return i?fe(3,1,e,t,n):0}function qe(e,t){if(i)return fe(4,1,e,t)}function Je(e,t){if(i)return fe(5,1,e,t)}function Ye(e,t,n){if(i)return fe(6,1,e,t,n)}function Xe(e,t,n){return i?fe(7,1,e,t,n):0}function Ze(e,t){if(i)return fe(8,1,e,t)}function Qe(e,t,n){if(i)return fe(9,1,e,t,n)}function $e(e,t,n,r){if(i)return fe(10,1,e,t,n,r)}function et(e,t,n,r){if(i)return fe(11,1,e,t,n,r)}function tt(e,t,n,r){if(i)return fe(12,1,e,t,n,r)}function nt(e){if(i)return fe(13,1,e)}function rt(e,t){if(i)return fe(14,1,e,t)}function it(e,t,n){if(i)return fe(15,1,e,t,n)}var at=()=>re(``),ot=e=>{e>>>=0;for(var t=``;;){var n=(C(),E)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},st={},ct={},lt={},ut=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function dt(e,t,n={}){return function(e,t,n={}){var r=t.name;if(!e)throw new ut(`type "${r}" must have a positive integer typeid pointer`);if(ct.hasOwnProperty(e)){if(n.de)return;throw new ut(`Cannot register type '${r}' twice`)}ct[e]=t,delete lt[e],st.hasOwnProperty(e)&&(t=st[e],delete st[e],t.forEach(e=>e()))}(e,t,n)}var ft=(e,t,n)=>{switch(t){case 1:return n?e=>(C(),T)[e>>>0]:e=>(C(),E)[e>>>0];case 2:return n?e=>(C(),D)[e>>>1>>>0]:e=>(C(),O)[e>>>1>>>0];case 4:return n?e=>(C(),k)[e>>>2>>>0]:e=>(C(),A)[e>>>2>>>0];case 8:return n?e=>(C(),N)[e>>>3>>>0]:e=>(C(),ee)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function pt(e,t,n,r,i){e>>>=0,n>>>=0,t=ot(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}dt(e,{name:t,Mc:a,Sc:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),Rc:ft(t,n,!r),Tc:null})}function mt(e,t,n,r){dt(e>>>=0,{name:t=ot(t>>>0),Mc:function(e){return!!e},Sc:function(e,t){return t?n:r},Rc:function(e){return this.Mc((C(),E)[e>>>0])},Tc:null})}var ht=[],gt=[0,1,,1,null,1,!0,1,!1,1];function _t(e){9<(e>>>=0)&&--gt[e+1]==0&&(gt[e]=void 0,ht.push(e))}var vt=e=>{if(!e)throw new ut(`Cannot use deleted val. handle = ${e}`);return gt[e]},yt=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=ht.pop()||gt.length;return gt[t]=e,gt[t+1]=1,t}};function bt(e){return this.Mc((C(),A)[e>>>2>>>0])}var xt={name:`emscripten::val`,Mc:e=>{var t=vt(e);return _t(e),t},Sc:(e,t)=>yt(t),Rc:bt,Tc:null};function St(e){return dt(e>>>0,xt)}var Ct=(e,t)=>{switch(t){case 4:return function(e){return this.Mc((C(),j)[e>>>2>>>0])};case 8:return function(e){return this.Mc((C(),M)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function wt(e,t,n){n>>>=0,dt(e>>>=0,{name:t=ot(t>>>0),Mc:e=>e,Sc:(e,t)=>t,Rc:Ct(t,n),Tc:null})}function Tt(e,t,n,r,i){e>>>=0,n>>>=0,t=ot(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<>>o,i=a(i)}dt(e,{name:t,Mc:a,Sc:(e,t)=>t,Rc:ft(t,n,r!==0),Tc:null})}function Et(e,t,n){function r(e){var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],new i((C(),T).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];dt(e>>>=0,{name:n=ot(n>>>0),Mc:r,Rc:r},{de:!0})}var Dt=(e,t,n)=>{var r=(C(),E);if(t>>>=0,0=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},Ot=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function kt(e,t){dt(e>>>=0,{name:t=ot(t>>>0),Mc(e){var t=(C(),A)[e>>>2>>>0];return t=Ge(e+4,t,!0),Ci(e),t},Sc(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new ut(`Cannot pass non-string to std::string`);var r=n?Ot(t):t.length,i=wi(4+r+1),a=i+4;return(C(),A)[i>>>2>>>0]=r,n?Dt(t,a,r+1):(C(),E).set(t,a>>>0),e!==null&&e.push(Ci,i),i},Rc:bt,Tc(e){Ci(e)}})}var At=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,jt=(e,t,n)=>{if(e>>>=1,16<(t=Ue((C(),O),e,t/2,n))-e&&At)return At.decode((C(),O).slice(e,t));for(n=``;e>>0];n+=String.fromCharCode(r)}return n},Mt=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i>>1>>>0]=a,t+=2}return(C(),D)[t>>>1>>>0]=0,t-r},Nt=e=>2*e.length,Pt=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(C(),A)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},Ft=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i>>2>>>0]=a,(t+=4)+4>n)break}return(C(),k)[t>>>2>>>0]=0,t-r},It=e=>{for(var t=0,n=0;n>>=0,t>>>=0,n=ot(n>>>=0),t===2)var r=jt,i=Mt,a=Nt;else r=Pt,i=Ft,a=It;dt(e,{name:n,Mc:e=>{var n=(C(),A)[e>>>2>>>0];return n=r(e+4,n*t,!0),Ci(e),n},Sc:(e,r)=>{if(typeof r!=`string`)throw new ut(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=wi(4+o+t);return(C(),A)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(Ci,s),s},Rc:bt,Tc(e){Ci(e)}})}function Rt(e,t){dt(e>>>=0,{ee:!0,name:t=ot(t>>>0),Mc:()=>{},Sc:()=>{}})}function zt(e){Ui(e>>>0,!r,1,!n,131072,!1),ye()}var Bt=e=>{if(!x)try{if(e(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ht(e){e>>>=0,Vt||(Atomics.waitAsync((C(),k),e>>>2,e).value.then(Ut),e+=128,Atomics.store((C(),k),e>>>2,1))}var Ut=()=>Bt(()=>{var e=Si();e&&(Ht(e),Yi())});function Wt(e,t){(e>>>=0)==t>>>0?setTimeout(Ut):i?postMessage({Vc:e,Oc:`checkMailbox`}):(e=_e[e])&&e.postMessage({Oc:`checkMailbox`})}var Gt=[];function Kt(e,t,n,r,i){for(t>>>=0,i>>>=0,Gt.length=0,n=i>>>3,r=i+r>>>3;n>>0]?(C(),N)[n++>>>0]:(C(),M)[n++>>>0];Gt.push(a)}return(t?qa[t]:Ka[e])(...Gt)}var qt=()=>{de=0};function Jt(e){e>>>=0,i?postMessage({Oc:`cleanupThread`,he:e}):ve(_e[e])}function Yt(e){}var Xt=e=>{try{e()}catch(e){re(e)}};function Zt(e){var t=(...t)=>{tn.push(e);try{return e(...t)}finally{x||(tn.pop(),$t&&Qt===1&&tn.length===0&&(Qt=0,de+=1,Xt(Ha),typeof Fibers<`u`&&Fibers.Be()))}};return an.set(e,t),t}var Qt=0,$t=null,en=0,tn=[],nn=new Map,rn=new Map,an=new Map,on=0,sn=null,cn=[],ln=e=>function(e){if(!x){if(Qt===0){var t=!1,n=!1;e((e=0)=>{if(!x&&(en=e,t=!0,n)){Qt=2,Xt(()=>Ua($t)),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.resume(),e=!1;try{var r=function(){var e=(C(),k)[$t+8>>>2>>>0];return e=rn.get(e),e=an.get(e),--de,e()}()}catch(t){r=t,e=!0}var i=!1;if(!$t){var a=sn;a&&(sn=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(Qt=1,$t=function(){var e=wi(65548),t=e+12;if((C(),A)[e>>>2>>>0]=t,(C(),A)[e+4>>>2>>>0]=t+65536,t=tn[0],!nn.has(t)){var n=on++;nn.set(t,n),rn.set(n,t)}return t=nn.get(t),(C(),k)[e+8>>>2>>>0]=t,e}(),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.pause(),Xt(()=>Va($t)))}else Qt===2?(Qt=0,Xt(Wa),Ci($t),$t=null,cn.forEach(Bt)):re(`invalid state: ${Qt}`);return en}}(t=>{e().then(t)});function un(e){return e>>>=0,ln(async()=>yt(await vt(e)))}var dn=[],fn=e=>{var t=dn.length;return dn.push(e),t},pn=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],o=ct[a];if(o===void 0)throw e=`parameter ${r}`,a=V(a),t=ot(a),Ci(a),new ut(`${e} has unknown type ${t}`);n[i]=o}return n},mn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((C(),A)[t>>>2>>>0]=yt(r)),e},hn={},gn=e=>{var t=hn[e];return t===void 0?ot(e):t};function _n(e,t,n){var[r,...i]=pn(e,t>>>0);t=r.Sc.bind(r);var a=i.map(e=>e.Rc.bind(e));e--;var o={toValue:vt};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=gn,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.ee||(o.toReturnWire=t,o.emval_returnValue=mn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) { + ${s} + }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,fn(Object.defineProperty(n,`name`,{value:s}))}function vn(e,t){return t>>>=0,(e=vt(e>>>0))==vt(t)}function yn(e){return(e>>>=0)?(e=gn(e),yt(globalThis[e])):yt(globalThis)}function bn(e){return e=gn(e>>>0),yt(t[e])}function xn(e,t){return t>>>=0,e=vt(e>>>0),t=vt(t),yt(e[t])}function Sn(e){9<(e>>>=0)&&(gt[e+1]+=1)}function Cn(e,t,n,r,i){return dn[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function wn(e,t,n,r,i){return Cn(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function Tn(){return yt([])}function En(e){e=vt(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function On(){return yt({})}function kn(e){for(var t=vt(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}_t(e)}function An(e,t,n){t>>>=0,n>>>=0,e=vt(e>>>0),t=vt(t),n=vt(n),e[t]=n}function jn(e,t){e=Ee(e),t>>>=0,e=new Date(1e3*e),(C(),k)[t>>>2>>>0]=e.getUTCSeconds(),(C(),k)[t+4>>>2>>>0]=e.getUTCMinutes(),(C(),k)[t+8>>>2>>>0]=e.getUTCHours(),(C(),k)[t+12>>>2>>>0]=e.getUTCDate(),(C(),k)[t+16>>>2>>>0]=e.getUTCMonth(),(C(),k)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(C(),k)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(C(),k)[t+28>>>2>>>0]=e}var Mn=e=>e%4==0&&(e%100!=0||e%400==0),Nn=[0,31,60,91,121,152,182,213,244,274,305,335],Pn=[0,31,59,90,120,151,181,212,243,273,304,334];function Fn(e,t){e=Ee(e),t>>>=0,e=new Date(1e3*e),(C(),k)[t>>>2>>>0]=e.getSeconds(),(C(),k)[t+4>>>2>>>0]=e.getMinutes(),(C(),k)[t+8>>>2>>>0]=e.getHours(),(C(),k)[t+12>>>2>>>0]=e.getDate(),(C(),k)[t+16>>>2>>>0]=e.getMonth(),(C(),k)[t+20>>>2>>>0]=e.getFullYear()-1900,(C(),k)[t+24>>>2>>>0]=e.getDay();var n=(Mn(e.getFullYear())?Nn:Pn)[e.getMonth()]+e.getDate()-1|0;(C(),k)[t+28>>>2>>>0]=n,(C(),k)[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),(C(),k)[t+32>>>2>>>0]=e}function In(e){e>>>=0;var t=new Date((C(),k)[e+20>>>2>>>0]+1900,(C(),k)[e+16>>>2>>>0],(C(),k)[e+12>>>2>>>0],(C(),k)[e+8>>>2>>>0],(C(),k)[e+4>>>2>>>0],(C(),k)[e>>>2>>>0],0),n=(C(),k)[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?(C(),k)[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=(Mn(t.getFullYear())?Nn:Pn)[t.getMonth()]+t.getDate()-1|0,(C(),k)[e+28>>>2>>>0]=n,(C(),k)[e>>>2>>>0]=t.getSeconds(),(C(),k)[e+4>>>2>>>0]=t.getMinutes(),(C(),k)[e+8>>>2>>>0]=t.getHours(),(C(),k)[e+12>>>2>>>0]=t.getDate(),(C(),k)[e+16>>>2>>>0]=t.getMonth(),(C(),k)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function Ln(e,t,n,r,a,o,s){return i?fe(16,1,e,t,n,r,a,o,s):-52}function Rn(e,t,n,r,a,o){if(i)return fe(17,1,e,t,n,r,a,o)}var zn={},Bn=()=>performance.timeOrigin+performance.now();function Vn(e,t){return i?fe(18,1,e,t):(zn[e]&&(clearTimeout(zn[e].id),delete zn[e]),t&&(zn[e]={id:setTimeout(()=>{delete zn[e],Bt(()=>Ji(e,performance.timeOrigin+performance.now()))},t),Ae:t}),0)}function Hn(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=new Date().getFullYear(),a=new Date(i,0,1).getTimezoneOffset();i=new Date(i,6,1).getTimezoneOffset();var o=Math.max(a,i);(C(),A)[e>>>2>>>0]=60*o,(C(),k)[t>>>2>>>0]=+(a!=i),e=(t=e=>{var t=Math.abs(e);return`UTC${0<=e?`-`:`+`}${String(Math.floor(t/60)).padStart(2,`0`)}${String(t%60).padStart(2,`0`)}`})(a),t=t(i),iDate.now(),Wn=1;function Gn(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!Wn)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(C(),N)[n>>>3>>>0]=BigInt(e),0}var Kn=[],qn=(e,t)=>{Kn.length=0;for(var n;n=(C(),E)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,Kn.push(n==112?(C(),A)[t>>>2>>>0]:n==106?(C(),N)[t>>>3>>>0]:n==105?(C(),k)[t>>>2>>>0]:(C(),M)[t>>>3>>>0]),t+=r?8:4}return Kn};function Jn(e,t,n){return e>>>=0,t=qn(t>>>0,n>>>0),qa[e](...t)}function Yn(e,t,n){return e>>>=0,t=qn(t>>>0,n>>>0),qa[e](...t)}var Xn=()=>{};function Zn(e,t){return b(Ge(e>>>0,t>>>0))}var Qn=()=>{throw de+=1,`unwind`};function $n(){return 4294901760}var er=()=>1,tr=()=>navigator.hardwareConcurrency;function nr(e){e>>>=0;var t=(C(),E).length;if(e<=t||4294901760=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);e:{r=(Math.min(4294901760,65536*Math.ceil(Math.max(e,r)/65536))-Se.buffer.byteLength+65535)/65536|0;try{Se.grow(r),F();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}var rr=e=>{var t=Ot(e)+1,n=ea(t);return Dt(e,n,t),n},ir=(e,t)=>{(C(),A)[e>>>2>>>0]=t;var n=(C(),A)[e>>>2>>>0];(C(),A)[e+4>>>2>>>0]=(t-n)/4294967296},ar=e=>(C(),A)[e>>>2>>>0]+4294967296*(C(),k)[e+4>>>2>>>0],or=[],sr=(e,t)=>{or[e>>>0]=t},cr=[],lr=[],ur=(e,t)=>{lr[e]=new Promise(n=>t.finally(()=>n(e)))},B=e=>{if(e)return or[e>>>0]},dr=(e,t)=>{for(e=(C(),A)[e>>>2>>>0];e;e=(C(),A)[e>>>2>>>0])t[(C(),k)[e+4>>>2>>>0]](e)},fr=(e,t,n)=>{(C(),A)[e>>>2>>>0]=t,(C(),A)[e+4>>>2>>>0]=n},pr=e=>{var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],Ge(t,e)},mr=e=>{var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],t?Ge(t,e):e===0?``:void 0},hr=e=>{var t=mr(e+4),n=(n=(C(),A)[e+12>>>2>>>0])?B(n):`auto`;if(e+=16){var r=B((C(),A)[e+4>>>2>>>0]),i=(C(),A)[e+16>>>2>>>0],a=(C(),A)[e+20>>>2>>>0];if(i){for(var o={},s=0;s>>3>>>0]}i=o}else i=void 0;e={module:r,constants:i,entryPoint:mr(e+8)}}else e=void 0;return{label:t,layout:n,compute:e}},gr=(e,t)=>{function n(n,r){n=e[n],(C(),A)[t+r>>>2>>>0]=n}n(`maxTextureDimension1D`,4),n(`maxTextureDimension2D`,8),n(`maxTextureDimension3D`,12),n(`maxTextureArrayLayers`,16),n(`maxBindGroups`,20),n(`maxBindGroupsPlusVertexBuffers`,24),n(`maxBindingsPerBindGroup`,28),n(`maxDynamicUniformBuffersPerPipelineLayout`,32),n(`maxDynamicStorageBuffersPerPipelineLayout`,36),n(`maxSampledTexturesPerShaderStage`,40),n(`maxSamplersPerShaderStage`,44),n(`maxStorageBuffersPerShaderStage`,48),n(`maxStorageTexturesPerShaderStage`,52),n(`maxUniformBuffersPerShaderStage`,56),n(`minUniformBufferOffsetAlignment`,80),n(`minStorageBufferOffsetAlignment`,84),ir(t+64,e.maxUniformBufferBindingSize),ir(t+72,e.maxStorageBufferBindingSize),n(`maxVertexBuffers`,88),ir(t+96,e.maxBufferSize),n(`maxVertexAttributes`,104),n(`maxVertexBufferArrayStride`,108),n(`maxInterStageShaderVariables`,112),n(`maxColorAttachments`,116),n(`maxColorAttachmentBytesPerSample`,120),n(`maxComputeWorkgroupStorageSize`,124),n(`maxComputeInvocationsPerWorkgroup`,128),n(`maxComputeWorkgroupSizeX`,132),n(`maxComputeWorkgroupSizeY`,136),n(`maxComputeWorkgroupSizeZ`,140),n(`maxComputeWorkgroupsPerDimension`,144),e.ze!==void 0&&n(`maxImmediateSize`,148)},_r=[,`validation`,`out-of-memory`,`internal`],vr=[,`compatibility`,`core`],yr={1:`core-features-and-limits`,2:`depth-clip-control`,3:`depth32float-stencil8`,4:`texture-compression-bc`,5:`texture-compression-bc-sliced-3d`,6:`texture-compression-etc2`,7:`texture-compression-astc`,8:`texture-compression-astc-sliced-3d`,9:`timestamp-query`,10:`indirect-first-instance`,11:`shader-f16`,12:`rg11b10ufloat-renderable`,13:`bgra8unorm-storage`,14:`float32-filterable`,15:`float32-blendable`,16:`clip-distances`,17:`dual-source-blending`,18:`subgroups`,19:`texture-formats-tier1`,20:`texture-formats-tier2`,21:`primitive-index`,22:`texture-component-swizzle`,327692:`chromium-experimental-unorm16-texture-formats`,327729:`chromium-experimental-multi-draw-indirect`},br=[,`low-power`,`high-performance`],xr=[,`occlusion`,`timestamp`],Sr={undefined:1,unknown:1,destroyed:2};function Cr(e,t,n,r,i,a){t=Ee(t),n=Ee(n),r>>>=0,i>>>=0,a>>>=0;var o=B(e>>>0);if(e={},a){var s=(C(),A)[a+12>>>2>>>0];if(s){var c=(C(),A)[a+16>>>2>>>0];e.requiredFeatures=Array.from((C(),A).subarray(c>>>2>>>0,c+4*s>>>2>>>0),e=>yr[e])}var l=(C(),A)[a+20>>>2>>>0];if(l){let t=function(e,t,n=!1){t=l+t,(t=(C(),A)[t>>>2>>>0])==4294967295||n&&t==0||(u[e]=t)},n=function(e,t){t=l+t;var n=(C(),A)[t>>>2>>>0],r=(C(),A)[t+4>>>2>>>0];n==4294967295&&r==4294967295||(u[e]=ar(t))};var u={};t(`maxTextureDimension1D`,4),t(`maxTextureDimension2D`,8),t(`maxTextureDimension3D`,12),t(`maxTextureArrayLayers`,16),t(`maxBindGroups`,20),t(`maxBindGroupsPlusVertexBuffers`,24),t(`maxDynamicUniformBuffersPerPipelineLayout`,32),t(`maxDynamicStorageBuffersPerPipelineLayout`,36),t(`maxSampledTexturesPerShaderStage`,40),t(`maxSamplersPerShaderStage`,44),t(`maxStorageBuffersPerShaderStage`,48),t(`maxStorageTexturesPerShaderStage`,52),t(`maxUniformBuffersPerShaderStage`,56),t(`minUniformBufferOffsetAlignment`,80),t(`minStorageBufferOffsetAlignment`,84),n(`maxUniformBufferBindingSize`,64),n(`maxStorageBufferBindingSize`,72),t(`maxVertexBuffers`,88),n(`maxBufferSize`,96),t(`maxVertexAttributes`,104),t(`maxVertexBufferArrayStride`,108),t(`maxInterStageShaderVariables`,112),t(`maxColorAttachments`,116),t(`maxColorAttachmentBytesPerSample`,120),t(`maxComputeWorkgroupStorageSize`,124),t(`maxComputeInvocationsPerWorkgroup`,128),t(`maxComputeWorkgroupSizeX`,132),t(`maxComputeWorkgroupSizeY`,136),t(`maxComputeWorkgroupSizeZ`,140),t(`maxComputeWorkgroupsPerDimension`,144),t(`maxImmediateSize`,148,!0),e.requiredLimits=u}(s=(C(),A)[a+24>>>2>>>0])&&(s={label:mr(s+4)},e.defaultQueue=s),e.label=mr(a+4)}de+=1,ur(t,o.requestDevice(e).then(e=>{--de,Bt(()=>{or[i>>>0]=e.queue,or[r>>>0]=e,de+=1,ur(n,e.lost.then(t=>{Bt(()=>{e.onuncapturederror=()=>{};var r=U(),i=rr(t.message);Li(n,Sr[t.reason],i),H(r)}),--de})),e.onuncapturederror=e=>{var t=5;e.error instanceof GPUValidationError?t=2:e.error instanceof GPUOutOfMemoryError?t=3:e.error instanceof GPUInternalError&&(t=4);var n=U();e=rr(e.error.message),Hi(r,t,e),H(n)},`adapterInfo`in e||(e.adapterInfo=o.info),Vi(t,1,r,0)})},e=>{--de,Bt(()=>{var i=U(),a=rr(e.message);Vi(t,3,r,a),n&&Li(n,4,a),H(i)})}))}function wr(e){var t=B(e>>>=0),n=cr[e];if(n){for(var r=0;r>>=0;var r=B(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=Xi(16,i.byteLength);return(C(),E).set(new Uint8Array(i),a>>>0),cr[e].push(()=>Ci(a)),a}function Er(e,t,n){n>>>=0;var r=B(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=Xi(16,i.byteLength);return(C(),E).fill(0,a,i.byteLength),cr[e].push(()=>{new Uint8Array(i).set((C(),E).subarray(a>>>0,a+i.byteLength>>>0)),Ci(a)}),a}function Dr(e,t,n,r,i){e>>>=0,t=Ee(t),n=Ee(n),i>>>=0;var a=B(e);cr[e]=[],i==4294967295&&(i=void 0),de+=1,ur(t,a.mapAsync(n,r>>>0,i).then(()=>{--de,Bt(()=>{Ri(t,1,0)})},n=>{--de,Bt(()=>{U();var r=rr(n.message);Ri(t,n.name===`AbortError`?4:n.name===`OperationError`?3:0,r),delete cr[e]})}))}function Or(e){var t=B(e>>>=0),n=cr[e];if(n){for(var r=0;r>>0]}function Ar(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=!!(C(),A)[t+32>>>2>>>0];t={label:mr(t+4),usage:(C(),A)[t+16>>>2>>>0],size:ar(t+24),mappedAtCreation:r},e=B(e);try{var i=e.createBuffer(t)}catch{return!1}return or[n>>>0]=i,r&&(cr[n]=[]),!0}function jr(e,t,n,r){e>>>=0,t=Ee(t),r>>>=0,n=hr(n>>>0),e=B(e),de+=1,ur(t,e.createComputePipelineAsync(n).then(e=>{--de,Bt(()=>{or[r>>>0]=e,Ii(t,1,r,0)})},e=>{--de,Bt(()=>{var n=U(),i=rr(e.message);Ii(t,e.reason===`validation`?3:e.reason===`internal`?4:0,r,i),H(n)})}))}function Mr(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=(C(),A)[t>>>2>>>0],i=(C(),k)[r+4>>>2>>>0];t={label:mr(t+4),code:``},i===2&&(t.code=pr(r+8)),e=B(e).createShaderModule(t),or[n>>>0]=e}var Nr=e=>{(e=B(e)).onuncapturederror=null,e.destroy()};function Pr(e,t){t=Ee(t),e=B(e>>>0),de+=1,ur(t,e.popErrorScope().then(e=>{--de,Bt(()=>{var n=5;e?e instanceof GPUValidationError?n=2:e instanceof GPUOutOfMemoryError?n=3:e instanceof GPUInternalError&&(n=4):n=1;var r=U(),i=e?rr(e.message):0;zi(t,1,n,i),H(r)})},e=>{--de,Bt(()=>{var n=U(),r=rr(e.message);zi(t,1,5,r),H(n)})}))}function Fr(e,t,n,r){if(t=Ee(t),r>>>=0,n>>>=0){var i={featureLevel:vr[(C(),k)[n+4>>>2>>>0]],powerPreference:br[(C(),k)[n+8>>>2>>>0]],forceFallbackAdapter:!!(C(),A)[n+12>>>2>>>0]};(e=(C(),A)[n>>>2>>>0])!==0&&(C(),i.De=!!(C(),A)[e+8>>>2>>>0])}`gpu`in navigator?(de+=1,ur(t,navigator.gpu.requestAdapter(i).then(e=>{--de,Bt(()=>{if(e)or[r>>>0]=e,Bi(t,1,r,0);else{var n=U(),i=rr(`WebGPU not available on this browser (requestAdapter returned null)`);Bi(t,3,r,i),H(n)}})},e=>{--de,Bt(()=>{var n=U(),i=rr(e.message);Bi(t,4,r,i),H(n)})}))):(i=U(),e=rr(`WebGPU not available on this browser (navigator.gpu is not available)`),Bi(t,3,r,e),H(i))}function Ir(e,t,n){return e>>>=0,t>>>=0,n>>>=0,ln(async()=>{var r=[];if(n){var i=(C(),k)[n>>>2>>>0];r.length=t+1,r[t]=new Promise(e=>setTimeout(e,i,0))}else r.length=t;for(var a=0;a{if(!Lr){var e,t={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(globalThis.navigator?.language??`C`).replace(`-`,`_`)+`.UTF-8`,_:`./this.program`};for(e in Rr)Rr[e]===void 0?delete t[e]:t[e]=Rr[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);Lr=n}return Lr};function Br(e,t){if(i)return fe(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of zr()){var o=t+r;(C(),A)[e+a>>>2>>>0]=o,r+=Dt(n,o,1/0)+1,a+=4}return 0}function Vr(e,t){if(i)return fe(20,1,e,t);e>>>=0,t>>>=0;var n=zr();for(var r of((C(),A)[e>>>2>>>0]=n.length,e=0,n))e+=Ot(r)+1;return(C(),A)[t>>>2>>>0]=e,0}function Hr(e){return i?fe(21,1,e):52}function Ur(e,t,n,r){return i?fe(22,1,e,t,n,r):52}function Wr(e,t,n,r){return i?fe(23,1,e,t,n,r):70}var Gr=[null,[],[]];function Kr(e,t,n,r){if(i)return fe(24,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o>>2>>>0],c=(C(),A)[t+4>>>2>>>0];t+=8;for(var l=0;l>>0],f=Gr[u];d===0||d===10?((u===1?y:b)(We(f)),f.length=0):f.push(d)}a+=c}return(C(),A)[r>>>2>>>0]=a,0}function qr(e){return e>>>0}function Jr(e,t){return gr(B(e>>>0).limits,t>>>0),1}function Yr(e,t){return B(e>>>0).features.has(yr[t])}function Xr(e){return BigInt(B(e>>>0).size)}function Zr(e){return BigInt(B(e>>>0).usage)}function Qr(e,t){if(e>>>=0,t>>>=0){var n=mr(t+4);n={label:n,timestampWrites:t=(t=(C(),A)[t+12>>>2>>>0])===0?void 0:{querySet:B((C(),A)[t+4>>>2>>>0]),beginningOfPassWriteIndex:(C(),A)[t+8>>>2>>>0],endOfPassWriteIndex:(C(),A)[t+12>>>2>>>0]}}}return t=B(e),e=ji(0),n=t.beginComputePass(n),or[e>>>0]=n,e}function $r(e,t,n,r){n=Ee(n),(r=Ee(r))==-1&&(r=void 0),(e=B(e>>>0)).clearBuffer(B(t>>>0),n,r)}function ei(e,t,n,r,i,a){n=Ee(n),i=Ee(i),a=Ee(a),B(e>>>0).copyBufferToBuffer(B(t>>>0),n,B(r>>>0),i,a)}function ti(e){var t=B(e>>>0);return e=ki(0),t=t.finish(),or[e>>>0]=t,e}function ni(e,t,n,r,i,a){a=Ee(a),B(e>>>0).resolveQuerySet(B(t>>>0),n,r,B(i>>>0),a)}function ri(e,t,n,r){B(e>>>0).dispatchWorkgroups(t,n,r)}function ii(e,t,n){n=Ee(n),B(e>>>0).dispatchWorkgroupsIndirect(B(t>>>0),n)}function ai(e){B(e>>>0).end()}function oi(e,t,n,r,i){r>>>=0,i>>>=0,e=B(e>>>0),n=B(n>>>0),r==0?e.setBindGroup(t,n):e.setBindGroup(t,n,(C(),A),i>>>2,r)}function si(e,t){B(e>>>0).setPipeline(B(t>>>0))}function ci(e,t,n){B(e>>>0).Ce(B(t>>>0),n)}function li(e,t){var n=B(e>>>0);return e=Oi(0),t=n.getBindGroupLayout(t),or[e>>>0]=t,e}function ui(e,t){function n(e){var t=(C(),A)[e+8>>>2>>>0],n=(C(),A)[e+32>>>2>>>0],r=(C(),A)[e+36>>>2>>>0],i=0;return dr(e,{327681:e=>{i=(C(),A)[e+8>>>2>>>0]}}),t?((n=ar(e+24))==-1&&(n=void 0),t={buffer:B(t),offset:ar(e+16),size:n}):t=B(n||r||i),{binding:(C(),A)[e+4>>>2>>>0],resource:t}}e>>>=0,t={label:mr(4+(t>>>=0)),layout:B((C(),A)[t+12>>>2>>>0]),entries:function(e,t){for(var r=[],i=0;i>>2>>>0],(C(),A)[t+20>>>2>>>0])},e=B(e);var r=Di(0);return sr(r,e.createBindGroup(t)),r}function di(e,t){var n;return e>>>=0,(t>>>=0)&&(n={label:mr(t+4)}),t=B(e),e=Ai(0),n=t.createCommandEncoder(n),or[e>>>0]=n,e}function fi(e,t){e>>>=0,t>>>=0,t={type:xr[(C(),k)[t+12>>>2>>>0]],count:(C(),A)[t+16>>>2>>>0]};var n=B(e);return e=Mi(0),t=n.createQuerySet(t),or[e>>>0]=t,e}function pi(e,t){e=B(e>>>0).adapterInfo,t>>>=0,(C(),A)[t+52>>>2>>>0]=e.subgroupMinSize,(C(),A)[t+56>>>2>>>0]=e.subgroupMaxSize;var n=e.vendor+e.architecture+e.device+e.description,r=Ot(n)+1,i=wi(r);return i&&Dt(n,i,r),n=i,r=Ot(e.vendor),fr(t+4,n,r),n+=r,r=Ot(e.architecture),fr(t+12,n,r),n+=r,r=Ot(e.device),fr(t+20,n,r),fr(t+28,n+r,Ot(e.description)),(C(),k)[t+36>>>2>>>0]=2,e=e.isFallbackAdapter?3:4,(C(),k)[t+40>>>2>>>0]=e,(C(),A)[t+44>>>2>>>0]=0,(C(),A)[t+48>>>2>>>0]=0,1}var mi={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function hi(e,t){t>>>=0;var n=B(e>>>0);e=wi(4*n.features.size);var r=0,i=0;for(let t of n.features)0<=(n=mi[t])&&((C(),k)[e+r>>>2>>>0]=n,r+=4,i++);(C(),A)[t+4>>>2>>>0]=e,(C(),A)[t>>>2>>>0]=i}function gi(e,t){return gr(B(e>>>0).limits,t>>>0),1}function _i(e,t){B(e>>>0).pushErrorScope(_r[t])}function vi(e,t,n){t>>>=0,n>>>=0,e=B(e>>>0),t=Array.from((C(),k).subarray(n>>>2>>>0,n+4*t>>>2>>>0),e=>B(e)),e.submit(t)}function yi(e,t,n,r,i){n=Ee(n),r>>>=0,i>>>=0,e=B(e>>>0),t=B(t>>>0),r=(C(),E).subarray(r>>>0,r+i>>>0),e.writeBuffer(t,n,r,0,i)}i||function(){for(var e=t.numThreads-1;e--;)xe();se.push(async()=>{var e=async function(){if(!i)return Promise.all(he.map(be))}();ce++,await e,--ce==0&&le&&(e=le,le=null,e())})}(),i||(Se=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),F()),t.wasmBinary&&(d=t.wasmBinary),t.stackSave=()=>U(),t.stackRestore=e=>H(e),t.stackAlloc=e=>ea(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(C(),T)[e>>>0]=t;break;case`i16`:(C(),D)[e>>>1>>>0]=t;break;case`i32`:(C(),k)[e>>>2>>>0]=t;break;case`i64`:(C(),N)[e>>>3>>>0]=BigInt(t);break;case`float`:(C(),j)[e>>>2>>>0]=t;break;case`double`:(C(),M)[e>>>3>>>0]=t;break;case`*`:(C(),A)[e>>>2>>>0]=t;break;default:re(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(C(),T)[e>>>0];case`i16`:return(C(),D)[e>>>1>>>0];case`i32`:return(C(),k)[e>>>2>>>0];case`i64`:return(C(),N)[e>>>3>>>0];case`float`:return(C(),j)[e>>>2>>>0];case`double`:return(C(),M)[e>>>3>>>0];case`*`:return(C(),A)[e>>>2>>>0];default:re(`invalid type for getValue: ${t}`)}},t.UTF8ToString=Ge,t.stringToUTF8=Dt,t.lengthBytesUTF8=Ot;var V,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,H,ea,U,ta,na,ra,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka=[pe,me,ze,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,Ln,Rn,Vn,Br,Vr,Hr,Ur,Wr,Kr],qa={969132:(e,n,r,i,a)=>{if(t===void 0||!t.Uc)return 1;if((e=Ge(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.Uc.get(e)))return 2;if(n=Number(n>>>0),r=Number(r>>>0),i=Number(i>>>0),n+r>e.byteLength)return 3;try{let o=e.subarray(n,n+r);switch(a){case 0:(C(),E).set(o,i>>>0);break;case 1:t.ad?t.ad(i,o):t.ne(i,o);break;default:return 4}return 0}catch{return 4}},969956:(e,n,r)=>{t.Sd(e,(C(),E).subarray(n>>>0,n+r>>>0))},970020:()=>t.le(),970062:e=>{t.jd(e)},970099:()=>typeof wasmOffsetConverter<`u`};function Ja(e,t,n,r){var i=U();try{return ma(e,t,n,r)}catch(e){if(H(i),e!==e+0)throw e;Zi(1,0)}}function Ya(e,t,n){var r=U();try{return da(e,t,n)}catch(e){if(H(r),e!==e+0)throw e;Zi(1,0)}}function Xa(e){var t=U();try{sa(e)}catch(e){if(H(t),e!==e+0)throw e;Zi(1,0)}}function Za(e,t){var n=U();try{return oa(e,t)}catch(e){if(H(n),e!==e+0)throw e;Zi(1,0)}}function W(e,t,n){var r=U();try{aa(e,t,n)}catch(e){if(H(r),e!==e+0)throw e;Zi(1,0)}}function Qa(e,t){var n=U();try{ha(e,t)}catch(e){if(H(n),e!==e+0)throw e;Zi(1,0)}}function $a(e,t,n,r,i,a,o){var s=U();try{return ua(e,t,n,r,i,a,o)}catch(e){if(H(s),e!==e+0)throw e;Zi(1,0)}}function eo(e,t,n,r,i,a){var o=U();try{ca(e,t,n,r,i,a)}catch(e){if(H(o),e!==e+0)throw e;Zi(1,0)}}function to(e,t,n,r){var i=U();try{pa(e,t,n,r)}catch(e){if(H(i),e!==e+0)throw e;Zi(1,0)}}function no(e,t,n,r,i,a,o){var s=U();try{_a(e,t,n,r,i,a,o)}catch(e){if(H(s),e!==e+0)throw e;Zi(1,0)}}function ro(e,t,n,r,i,a,o){var s=U();try{va(e,t,n,r,i,a,o)}catch(e){if(H(s),e!==e+0)throw e;Zi(1,0)}}function io(e,t,n,r,i,a,o,s){var c=U();try{Da(e,t,n,r,i,a,o,s)}catch(e){if(H(c),e!==e+0)throw e;Zi(1,0)}}function ao(e,t,n,r,i,a,o,s,c,l,u,d){var f=U();try{ya(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(H(f),e!==e+0)throw e;Zi(1,0)}}function oo(e,t,n,r,i){var a=U();try{return ga(e,t,n,r,i)}catch(e){if(H(a),e!==e+0)throw e;Zi(1,0)}}function so(e,t,n,r,i){var a=U();try{la(e,t,n,r,i)}catch(e){if(H(a),e!==e+0)throw e;Zi(1,0)}}function co(e,t,n,r,i,a,o,s){var c=U();try{fa(e,t,n,r,i,a,o,s)}catch(e){if(H(c),e!==e+0)throw e;Zi(1,0)}}function lo(e){var t=U();try{return Oa(e)}catch(e){if(H(t),e!==e+0)throw e;Zi(1,0)}}function uo(e,t,n){var r=U();try{return ka(e,t,n)}catch(e){if(H(r),e!==e+0)throw e;Zi(1,0)}}function fo(e,t){var n=U();try{return Ba(e,t)}catch(e){if(H(n),e!==e+0)throw e;return Zi(1,0),0n}}function po(e){var t=U();try{return ba(e)}catch(e){if(H(t),e!==e+0)throw e;return Zi(1,0),0n}}function mo(e,t,n,r){var i=U();try{return Aa(e,t,n,r)}catch(e){if(H(i),e!==e+0)throw e;Zi(1,0)}}function ho(e,t,n,r,i){var a=U();try{return ja(e,t,n,r,i)}catch(e){if(H(a),e!==e+0)throw e;Zi(1,0)}}function go(e,t,n,r,i,a){var o=U();try{return Ma(e,t,n,r,i,a)}catch(e){if(H(o),e!==e+0)throw e;Zi(1,0)}}function _o(e,t,n,r,i,a){var o=U();try{return Ta(e,t,n,r,i,a)}catch(e){if(H(o),e!==e+0)throw e;Zi(1,0)}}function vo(e,t,n,r,i,a){var o=U();try{return Na(e,t,n,r,i,a)}catch(e){if(H(o),e!==e+0)throw e;Zi(1,0)}}function yo(e,t,n,r,i,a,o,s){var c=U();try{return Ea(e,t,n,r,i,a,o,s)}catch(e){if(H(c),e!==e+0)throw e;Zi(1,0)}}function bo(e,t,n,r,i){var a=U();try{return Pa(e,t,n,r,i)}catch(e){if(H(a),e!==e+0)throw e;return Zi(1,0),0n}}function xo(e,t,n,r){var i=U();try{return Fa(e,t,n,r)}catch(e){if(H(i),e!==e+0)throw e;Zi(1,0)}}function So(e,t,n,r){var i=U();try{return Ia(e,t,n,r)}catch(e){if(H(i),e!==e+0)throw e;Zi(1,0)}}function Co(e,t,n,r,i,a,o,s,c,l,u,d){var f=U();try{return La(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(H(f),e!==e+0)throw e;Zi(1,0)}}function wo(e,t,n,r,i,a,o,s,c,l,u){var d=U();try{Ra(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(H(d),e!==e+0)throw e;Zi(1,0)}}function To(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=U();try{za(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(H(g),e!==e+0)throw e;Zi(1,0)}}function Eo(e,t,n){var r=U();try{return Sa(e,t,n)}catch(e){if(H(r),e!==e+0)throw e;return Zi(1,0),0n}}function Do(e,t,n){var r=U();try{return xa(e,t,n)}catch(e){if(H(r),e!==e+0)throw e;Zi(1,0)}}function Oo(e,t,n){var r=U();try{return Ca(e,t,n)}catch(e){if(H(r),e!==e+0)throw e;Zi(1,0)}}function ko(e,t,n,r){var i=U();try{wa(e,t,n,r)}catch(e){if(H(i),e!==e+0)throw e;Zi(1,0)}}function Ao(){if(0{let n=new WeakMap,r,i,a=1;t.webgpuRegisterDevice=e=>{if(i!==void 0)throw Error(`another WebGPU EP inference session is being created.`);if(e){var t=n.get(e);if(!t){let r=((e,t=0)=>{var n=Fi(t);return t=Pi(t,n),or[n>>>0]=e.queue,or[t>>>0]=e,t})(e,t=Ei(0));t=[a++,t,r],n.set(e,t)}return r=e,i=t[0],t}r=void 0,i=0};let o=new Map;t.webgpuOnCreateSession=t=>{if(i!==void 0){var n=i;if(i=void 0,t){let i=xi(n);o.set(t,i),n===0&&e(r??B(i))}r=void 0}},t.webgpuOnReleaseSession=e=>{o.delete(e)};let s=Symbol(`gpuBufferMetadata`);t.webgpuRegisterBuffer=(e,t,n)=>{if(n)return e[s]=[n,NaN],n;if(n=e[s])return n[1]++,n[0];if((t=o.get(t))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);return t=((e,t=0)=>(e.mapState===`unmapped`||re(),t=Ni(t),or[t>>>0]=e,t))(e,t),e[s]=[t,1],t},t.webgpuUnregisterBuffer=e=>{let t=e[s];if(!t)throw Error(`Buffer is not registered`);t[1]--,t[1]===0&&(Ti(t[0]),delete e[s])},t.webgpuGetBuffer=e=>B(e),t.webgpuCreateDownloader=(e,t,n)=>{if((n=o.get(n))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);let r=B(n),i=16*Math.ceil(Number(t)/16);return async()=>{let n=r.createBuffer({size:i,usage:9});try{let a=r.createCommandEncoder();return a.copyBufferToBuffer(e,0,n,0,i),r.queue.submit([a.finish()]),await n.mapAsync(GPUMapMode.READ),n.getMappedRange().slice(0,t)}finally{n.destroy()}}},t.ad=(e,t)=>{var n=t.buffer;let a=t.byteOffset,o=t.byteLength;if(t=16*Math.ceil(Number(o)/16),e=B(e),!r){var s=xi(i);r=B(s)}let c=(s=r.createBuffer({mappedAtCreation:!0,size:t,usage:6})).getMappedRange();new Uint8Array(c).set(new Uint8Array(n,a,o)),s.unmap(),(n=r.createCommandEncoder()).copyBufferToBuffer(s,0,e,0,t),r.queue.submit([n.finish()]),s.destroy()}},t.webnnInit=e=>{let n=e[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=e.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=e=>n.onRunStart(e),t.webnnOnRunEnd=n.onRunEnd.bind(n),t.webnnOnReleaseSession=e=>{n.onReleaseSession(e)},t.webnnCreateMLTensorDownloader=(e,t)=>n.createMLTensorDownloader(e,t),t.webnnRegisterMLTensor=(e,t,r,i)=>n.registerMLTensor(e,t,r,i),t.webnnCreateMLContext=e=>n.createMLContext(e),t.webnnRegisterMLConstant=(e,r,i,a,o,s)=>n.registerMLConstant(e,r,i,a,o,t.Uc,s),t.webnnRegisterGraphInput=n.registerGraphInput.bind(n),t.webnnIsGraphInput=n.isGraphInput.bind(n),t.webnnRegisterGraphOutput=n.registerGraphOutput.bind(n),t.webnnIsGraphOutput=n.isGraphOutput.bind(n),t.webnnCreateTemporaryTensor=n.createTemporaryTensor.bind(n),t.webnnIsGraphInputOutputTypeSupported=n.isGraphInputOutputTypeSupported.bind(n)},P?t:new Promise((e,t)=>{m=e,h=t})}var Ye,Xe,Ze=w(()=>{Ye=Je,Xe=globalThis.self?.name?.startsWith(`em-pthread`),Xe&&Je()}),Qe,$e,et,tt,nt,rt,it,at,ot,st,ct,lt,ut,dt,ft=w(()=>{Ve(),Qe=typeof location>`u`?void 0:location.origin,$e=import.meta.url>`file:`&&import.meta.url<`file;`,et=()=>$e?new URL(new URL(`ort.webgpu.bundle.min.mjs`,import.meta.url).href,Qe).href:import.meta.url,tt=et(),nt=()=>{if(tt&&!tt.startsWith(`blob:`))return tt.substring(0,tt.lastIndexOf(`/`)+1)},rt=(e,t)=>{try{let n=t??tt;return(n?new URL(e,n):new URL(e)).origin===Qe}catch{return!1}},it=(e,t)=>{let n=t??tt;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},at=(e,t)=>`${t??`./`}${e}`,ot=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},st=async e=>(await _(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,ct=(Ke(),D(He)).default,lt=async()=>{if(!tt)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(rt(tt))return[void 0,ct()];let e=await ot(tt);return[e,ct(e)]},ut=(Ze(),D(qe)).default,dt=async(e,t,n,r)=>{let i=ut&&!(e||t);if(i)if(tt)i=rt(tt)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,ut];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??it(r,t),a=n&&i&&!rt(i,t),o=a?await ot(i):i??at(r,t);return[a?o:void 0,await st(o)]}}}),pt,mt,ht,gt,_t,vt,yt,bt,xt,St=w(()=>{ft(),mt=!1,ht=!1,gt=!1,_t=()=>{if(typeof SharedArrayBuffer>`u`)return!1;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}},vt=()=>{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}},yt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},bt=async e=>{if(mt)return Promise.resolve();if(ht)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(gt)throw Error(`previous call to 'initializeWebAssembly()' failed.`);ht=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!yt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!vt())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=_t();n>1&&!r&&(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.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await dt(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=nt();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{ht=!1,mt=!0,pt=t,e(),d&&URL.revokeObjectURL(d)},e=>{ht=!1,gt=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},xt=()=>{if(mt&&pt)return pt;throw Error(`WebAssembly is not initialized yet.`)}}),Ct,wt,Tt,Et=w(()=>{St(),Ct=(e,t)=>{let n=xt(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},wt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)wt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},Tt=e=>{let t=xt(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),Dt,Ot=w(()=>{St(),Et(),Dt=e=>{let t=xt(),n=0,r=[],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 Error(`log severity 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 Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=Ct(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&Tt(`Can't create run options.`),e?.extra!==void 0&&wt(e.extra,``,new WeakSet,(e,i)=>{let a=Ct(e,r),o=Ct(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&Tt(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),kt,At,jt,Mt,Nt,Pt,Ft,It=w(()=>{St(),Et(),kt=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},At=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},jt=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Mt=(e,t,n,r)=>{let i=Ct(t,r),a=Ct(n,r);xt()._OrtAddSessionConfigEntry(e,i,a)!==0&&Tt(`Can't set a session config entry: ${t} - ${n}.`)},Nt=(e,t,n,r)=>{let i=Ct(t,r),a=Ct(n,r);e.push([i,a])},Pt=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,typeof i!=`string`){let t=i?.deviceType;t&&Mt(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device)if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`);let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&Nt(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&Nt(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];Nt(a,`forceCpuNodeNames`,e.join(` +`),n)}r.validationMode&&Nt(a,`validationMode`,r.validationMode,n)}let o=xt().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;Nt(a,`deviceId`,e.toString(),n),Nt(a,`webgpuInstance`,t.toString(),n),Nt(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=Ct(r,n),s=a.length,c=0,l=0;if(s>0){c=xt()._malloc(s*xt().PTR_SIZE),n.push(c),l=xt()._malloc(s*xt().PTR_SIZE),n.push(l);for(let e=0;e{let t=xt(),n=0,r=[],i=e||{};jt(i);try{let e=kt(i.graphOptimizationLevel??`all`),a=At(i.executionMode??`sequential`),o=typeof i.logId==`string`?Ct(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?Ct(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&Tt(`Can't create session options.`),i.executionProviders&&await Pt(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);Mt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=Ct(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&Tt(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&wt(i.extra,``,new WeakSet,(e,t)=>{Mt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Tt(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt=w(()=>{Lt=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;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},Rt=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`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},zt=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},Bt=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 Error(`unsupported type: ${e}`)}},Vt=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 Error(`unsupported logging level: ${e}`)}},Ht=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Ut=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Wt=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;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Kt,qt=w(()=>{Ve(),Kt=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Jt,Yt=w(()=>{Gt(),Jt=(e,t)=>new(Bt(t))(e)}),Xt,Zt,Qt,$t,en,tn,nn,rn=w(()=>{Gt(),Xt=[`V`,`I`,`W`,`E`,`F`],Zt=(e,t)=>{console.log(`[${Xt[e]},${new Date().toISOString()}]${t}`)},en=(e,t)=>{Qt=e,$t=t},tn=(e,t)=>{let n=Vt(e);n>=Vt(Qt)&&Zt(n,typeof t==`function`?t():t)},nn=(...e)=>{$t&&tn(...e)}}),an,on,sn,cn,ln,un,dn,fn,pn,mn,hn,gn=w(()=>{Gt(),rn(),an=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),on=(e,t)=>{if(t===`int32`)return e;let n=an.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(Bt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},sn=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},cn=1,ln=()=>cn++,un=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),dn=(e,t)=>{let n=an.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},fn=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return dn(this.dataType,this.tensorShape)}destroy(){nn(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=sn(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},pn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=un.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);nn(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==dn(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType===`int32`)t=on(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else nn(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?sn(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},mn=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=ln();return this.tensorTrackersById.set(e,new pn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){nn(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){nn(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=ln(),o=new fn({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new pn(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){nn(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}nn(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new fn({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},hn=(...e)=>new mn(...e)}),_n={};T(_n,{WebNNBackend:()=>bn});var vn,yn,bn,xn=w(()=>{Gt(),St(),Yt(),gn(),rn(),vn=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),yn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},bn=class{constructor(e){this.tensorManager=hn(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,en(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){nn(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){nn(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)nn(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}else if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>yn(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){nn(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=vn.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){nn(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=vn.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!xt().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);nn(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Jt(n,t)}}registerMLTensor(e,t,n,r){let i=vn.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return nn(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,n,r,i,a,o=!1){if(!a)throw Error(`External mounted files are not available.`);let s=e;e.startsWith(`./`)&&(s=e.substring(2));let c=a.get(s);if(!c)throw Error(`File with name ${s} not found in preloaded files.`);if(t+n>c.byteLength)throw Error(`Out of bounds: data offset and length exceed the external file data size.`);let l=c.slice(t,t+n).buffer,u;switch(i.dataType){case`float32`:u=new Float32Array(l);break;case`float16`:u=typeof Float16Array<`u`&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case`int32`:u=new Int32Array(l);break;case`uint32`:u=new Uint32Array(l);break;case`int64`:if(o){let e=on(new Uint8Array(l),`int64`);u=new Int32Array(e.buffer),i.dataType=`int32`}else u=new BigInt64Array(l);break;case`uint64`:u=new BigUint64Array(l);break;case`int8`:u=new Int8Array(l);break;case`int4`:case`uint4`:case`uint8`:u=new Uint8Array(l);break;default:throw Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return nn(`verbose`,()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${o?`(Note: it was int64 data type and registered to int32 as workaround)`:``}`),r.constant(i,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=vn.get(Lt(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn=w(()=>{Be(),Ot(),It(),Gt(),St(),Et(),qt(),Sn=(e,t)=>{xt()._OrtInit(e,t)!==0&&Tt(`Can't initialize onnxruntime.`)},Cn=async e=>{Sn(e.wasm.numThreads,Vt(e.logLevel))},wn=async(e,t)=>{xt().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&xt().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(xn(),D(_n)).WebNNBackend(e);xt().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},Tn=new Map,En=e=>{let t=xt(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&Tt(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},Dn=(e,t)=>{let n=xt(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&Tt(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e{let t=xt(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},kn=async(e,t)=>{let n,r,i=xt();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=On(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Ft(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Kt(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&Tt(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=En(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;te===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&Tt(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Wt(e))}),Tn.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&Tt(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&Tt(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&Tt(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},An=e=>{let t=xt(),n=Tn.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&Tt(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&Tt(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&Tt(`Can't release session.`),Tn.delete(e)},jn=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=xt(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=zt(Lt(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=zt(Lt(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,Lt(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;es.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(Lt(l),p,m,g,u.length,Wt(f));e===0&&Tt(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Mn=async(e,t,n,r,i,a)=>{let o=xt(),s=o.PTR_SIZE,c=Tn.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),T=o.stackAlloc(h*s),E=o.stackAlloc(g*s),D=o.stackAlloc(g*s);try{[_,v]=Dt(a),ke(`wasm prepareInputOutputTensor`);for(let r=0;re*t,1);u=Rt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=zt(a,g);if(i===void 0||!Ht(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(Bt(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&Tt(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(zt(a,g)===void 0||!Ut(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,O.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(Bt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&Tt(`Can't clear bound outputs.`),Tn.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(O))C[e][2]=t;return Ae(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},Nn=e=>{let t=xt(),n=Tn.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&Tt(`Can't get an profile file name.`),t._OrtFree(i)},Pn=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er=w(()=>{Be(),Fn(),St(),ft(),In=()=>!!I.wasm.proxy&&typeof document<`u`,Rn=!1,zn=!1,Bn=!1,Un=new Map,Wn=(e,t)=>{let n=Un.get(e);n?n.push(t):Un.set(e,[t])},Gn=()=>{if(Rn||!zn||Bn||!Ln)throw Error(`worker not ready`)},Kn=e=>{switch(e.data.type){case`init-wasm`:Rn=!1,e.data.err?(Bn=!0,Hn[1](e.data.err)):(zn=!0,Hn[0]()),Vn&&=(URL.revokeObjectURL(Vn),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Un.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},qn=async()=>{if(!zn){if(Rn)throw Error(`multiple calls to 'initWasm()' detected.`);if(Bn)throw Error(`previous call to 'initWasm()' failed.`);if(Rn=!0,In())return new Promise((e,t)=>{Ln?.terminate(),lt().then(([n,r])=>{try{Ln=r,Ln.onerror=e=>t(e),Ln.onmessage=Kn,Hn=[e,t];let i={type:`init-wasm`,in:I};!i.in.wasm.wasmPaths&&(n||$e)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.asyncify-CtKKja6V.wasm`,``+import.meta.url).href}),Ln.postMessage(i),Vn=n}catch(e){t(e)}},t)});try{await bt(I.wasm),await Cn(I),zn=!0}catch(e){throw Bn=!0,e}finally{Rn=!1}}},Jn=async e=>{if(In())return Gn(),new Promise((t,n)=>{Wn(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:I}};Ln.postMessage(r)});await wn(I,e)},Yn=async e=>In()?(Gn(),new Promise((t,n)=>{Wn(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};Ln.postMessage(r,[e.buffer])})):On(e),Xn=async(e,t)=>{if(In()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Gn(),new Promise((n,r)=>{Wn(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Ln.postMessage(i,a)})}else return kn(e,t)},Zn=async e=>{if(In())return Gn(),new Promise((t,n)=>{Wn(`release`,[t,n]);let r={type:`release`,in:e};Ln.postMessage(r)});An(e)},Qn=async(e,t,n,r,i,a)=>{if(In()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Gn(),new Promise((i,o)=>{Wn(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};Ln.postMessage(c,Pn(s))})}else return Mn(e,t,n,r,i,a)},$n=async e=>{if(In())return Gn(),new Promise((t,n)=>{Wn(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};Ln.postMessage(r)});Nn(e)}}),tr,nr,rr,ir=w(()=>{Be(),er(),Gt(),Ve(),qt(),tr=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},nr=e=>{switch(e[3]){case`cpu`:return new Ce(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!Ht(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return Ce.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Ut(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return Ce.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},rr=class{async fetchModelAndCopyToWasmMemory(e){return Yn(await Kt(e))}async loadModel(e,t){De();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Xn(n,t),Oe()}async dispose(){return Zn(this.sessionId)}async run(e,t,n){De();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>tr(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?tr(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Qn(this.sessionId,i,s,o,c,n),u={};for(let e=0;esr,initializeFlags:()=>or,wasmBackend:()=>cr});var or,sr,cr,lr=w(()=>{Be(),er(),ir(),or=()=>{(typeof I.wasm.initTimeout!=`number`||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let e=I.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!=`boolean`&&(I.wasm.proxy=!1),typeof I.wasm.trace!=`boolean`&&(I.wasm.trace=!1),typeof I.wasm.numThreads!=`number`||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let e=typeof navigator>`u`?C(`node:os`).cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},sr=class{async init(e){or(),await qn(),await Jn(e)}async createInferenceSessionHandler(e,t){let n=new rr;return await n.loadModel(e,t),n}},cr=new sr});Be(),Be(),Be();var ur=`1.26.0-dev.20260410-5e55544225`,B=ze;{let e=(lr(),D(ar)).wasmBackend;A(`webgpu`,e,5),A(`webnn`,e,5),A(`cpu`,e,10),A(`wasm`,e,10)}Object.defineProperty(I.versions,`web`,{value:ur,enumerable:!0});var dr=`1.24.3`,fr=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:dr},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);fr=e}},get logLevel(){return fr}},`logLevel`,{enumerable:!0});var pr=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,hr(o,s)}else throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(hr(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return hr(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},_r=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new Dr({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},vr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Dr({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},yr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Dr({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},br=(e,t,n)=>new Dr({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),xr=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),Sr=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),Cr=!1,wr=()=>{if(!Cr){Cr=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(xr.set(`int64`,BigInt64Array),Sr.set(BigInt64Array,`int64`)),t&&(xr.set(`uint64`,BigUint64Array),Sr.set(BigUint64Array,`uint64`)),r?(xr.set(`float16`,n),Sr.set(n,`float16`)):xr.set(`float16`,Uint16Array)}},Tr=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new Dr(e.type,e.data,t);case`cpu-pinned`:return new Dr({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new Dr({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new Dr({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new Dr({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}},Dr=class{constructor(e,t,n){wr();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=xr.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=xr.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=Sr.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=Tr(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw 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(e,t){return gr(e,t)}static fromTexture(e,t){return _r(e,t)}static fromGpuBuffer(e,t){return vr(e,t)}static fromMLTensor(e,t){return yr(e,t)}static fromPinnedBuffer(e,t,n){return br(e,t,n)}toDataURL(e){return pr(this,e)}toImageData(e){return mr(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let 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 Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return Er(this,e)}},Or=Dr,kr=Object.defineProperty,Ar=(e,t)=>{for(var n in t)kr(e,n,{get:t[n],enumerable:!0})},jr={},Mr={},Nr={},Pr=`4.1.0`,Fr=typeof self<`u`,Ir=!ci(jr),Lr=!ci(Mr),Rr=Fr&&`caches`in self,zr=globalThis.Deno!==void 0;globalThis.Bun;var Br=zr&&Rr&&!Ir,Vr=typeof process<`u`,Hr=Vr&&process?.release?.name===`node`&&!Br,Ur=typeof window<`u`&&window.document!==void 0,Wr=Fr&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),Gr=Ur||Wr||Br,Kr=Hr||typeof navigator<`u`&&`gpu`in navigator,qr=typeof navigator<`u`&&`ml`in navigator,Jr=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,Yr=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,Xr=typeof ServiceWorkerGlobalScope<`u`&&Fr&&self instanceof ServiceWorkerGlobalScope,Zr=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent,t=(navigator.vendor||``).indexOf(`Apple`)>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`);return t&&n})(),Qr=Object.freeze({IS_BROWSER_ENV:Ur,IS_WEBWORKER_ENV:Wr,IS_WEB_ENV:Gr,IS_SERVICE_WORKER_ENV:Xr,IS_DENO_WEB_RUNTIME:Br,IS_WEB_CACHE_AVAILABLE:Rr,IS_WEBGPU_AVAILABLE:Kr,IS_WEBNN_AVAILABLE:qr,IS_SAFARI:Zr,IS_PROCESS_AVAILABLE:Vr,IS_NODE_ENV:Hr,IS_FS_AVAILABLE:Ir,IS_PATH_AVAILABLE:Lr,IS_CRYPTO_AVAILABLE:Jr,IS_CHROME_AVAILABLE:Yr}),$r=Ir&&Lr,ei=`./`;if($r){let e=Object(import.meta).url;e?ei=Mr.dirname(Mr.dirname(Nr.fileURLToPath(e))):typeof __dirname<`u`&&(ei=Mr.dirname(__dirname))}var ti=$r?Mr.join(ei,`/.cache/`):null,ni=`/models/`,ri=$r?Mr.join(ei,ni):ni,ii=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,ai=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),oi=ai.WARNING,si={version:Pr,backends:{onnx:{}},get logLevel(){return oi},set logLevel(e){oi=e,si.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(Ur||Wr||Br),localModelPath:ri,useFS:Ir,useBrowserCache:Rr,useFSCache:Ir,cacheDir:ti,useCustomCache:!1,customCache:null,useWasmCache:Rr||Ir,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:ii};function ci(e){return Object.keys(e).length===0}var li=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function ui(e,t){e&&e(t)}var di=class extends li{constructor(e,t){super(),this.callback=e,this.files_loading=t}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function fi(e){return Number.isInteger(e)||typeof e==`bigint`}function pi(e){return e==null||e===-1}function mi(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function hi(...e){return Array.prototype.concat.apply([],e)}function gi(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function _i(e,t){return Math.abs((e+t)%(2*t)-t)}function vi(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function yi(e,t){let n=0;for(let r of e)r===t&&++n;return n}var V={error(...e){si.logLevel<=ai.ERROR&&console.error(...e)},warn(...e){si.logLevel<=ai.WARNING&&console.warn(...e)},info(...e){si.logLevel<=ai.INFO&&console.log(...e)},debug(...e){si.logLevel<=ai.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},bi=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let n of e){let e=t;for(let t=0;tr&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),Ci=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(Si),wi=`.,!?…。,、।۔،`,Ti=new Map([[`(?i:'s|'t|'re|'ve|'m|'ll|'d)`,`(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))`],[`(?i:[sdmt]|ll|ve|re)`,`(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`],[`[^\\r\\n\\p{L}\\p{N}]?+`,`[^\\r\\n\\p{L}\\p{N}]?`],[`[^\\s\\p{L}\\p{N}]++`,`[^\\s\\p{L}\\p{N}]+`],[`(?>\\p{Nd}{510})`,`(?:\\p{Nd}{510})`],[`\\p{Nd}{3}+`,`(?:\\p{Nd}{3})+`],[`\\G`,``],[` ?[^(\\s|[${wi}])]+`,` ?[^\\s${wi}]+`]]),Ei=`\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E`,Di=e=>e.replace(/ \./g,`.`).replace(/ \?/g,`?`).replace(/ \!/g,`!`).replace(/ ,/g,`,`).replace(/ \' /g,`'`).replace(/ n't/g,`n't`).replace(/ 'm/g,`'m`).replace(/ 's/g,`'s`).replace(/ 've/g,`'ve`).replace(/ 're/g,`'re`),Oi=(e,t=!0)=>{if(e.Regex!==void 0){let t=e.Regex.replace(/\\([#&~])/g,`$1`);t=t.replace(/\\A/g,`^`).replace(/\\z/g,`$`).replace(/\\Z/g,`(?=\\r?\\n?$)`);for(let[e,n]of Ti)t=t.replaceAll(e,n);try{return new RegExp(t,`gu`)}catch(e){if(!(e instanceof SyntaxError)||!e.message.toLowerCase().includes(`invalid property name`))throw e;let n=!1,r=t.replace(/(\\[pP])\{([^}=]+)\}/g,(e,t,r)=>{try{return RegExp(`\\p{${r}}`,`u`),`${t}{${r}}`}catch{return n=!0,`${t}{Script=${r}}`}});if(!n)throw e;try{return new RegExp(r,`gu`)}catch{throw e}}}else if(e.String!==void 0){let n=ki(e.String);return new RegExp(t?n:`(${n})`,`gu`)}else return console.warn(`Unknown pattern type:`,e),null},ki=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Ai=(e,t,n)=>{let r=[],i=0;for(;ie>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,Mi=e=>Number.isInteger(e)||typeof e==`bigint`,Ni=e=>{let t=0;for(let n of e)++t;return t},Pi=e=>Ri(e.toLowerCase()),Fi=(...e)=>Array.prototype.concat.apply([],e),Ii=e=>new Map(Object.entries(e)),Li=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r0&&n.push(t),r=i.index+t.length}return re.replace(/\p{M}/gu,``),zi=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a "${r}" property`;return null},Bi=e=>e.match(/\S+/g)||[],Vi=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Hi=class extends Vi{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},Ui=class extends Hi{tokenize_chinese_chars(e){let t=[];for(let n=0;ne.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},Gi=class extends Hi{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>ta(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},Ki=class extends Hi{normalize(e){let t=Oi(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??``)}},qi=class extends Hi{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},Ji=class extends qi{constructor(){super(...arguments),this.form=`NFC`}},Yi=class extends qi{constructor(){super(...arguments),this.form=`NFD`}},Xi=class extends qi{constructor(){super(...arguments),this.form=`NFKC`}},Zi=class extends qi{constructor(){super(...arguments),this.form=`NFKD`}},Qi=class extends Hi{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}},$i=class extends Hi{normalize(e){return Ri(e)}},H=class extends Hi{normalize(e){return e.toLowerCase()}},ea=class extends Hi{normalize(e){return e=this.config.prepend+e,e}};function U(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new Ui(e);case`Precompiled`:return new Wi(e);case`Sequence`:return new Gi(e);case`Replace`:return new Ki(e);case`NFC`:return new Ji(e);case`NFD`:return new Yi(e);case`NFKC`:return new Xi(e);case`NFKD`:return new Zi(e);case`Strip`:return new Qi(e);case`StripAccents`:return new $i(e);case`Lowercase`:return new H(e);case`Prepend`:return new ea(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var ta=U,na=class extends Vi{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},ra=class extends na{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,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=Si,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(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},ia=class extends na{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},aa=class extends na{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},oa=class extends na{constructor(e){super(),this.config=e,this.pattern=Oi(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):Li(e,this.pattern)}},sa=class extends na{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${Ei}]+|[${Ei}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},ca=class extends na{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?``:`+`}`;this.pattern=new RegExp(t,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},la=class extends na{constructor(){super(),this.pattern=RegExp(`[^\\s${Ei}]+|[${Ei}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},ua=class extends na{constructor(e){super(),this.config=e,this.pattern=Oi(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},da=class extends na{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>ha(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},fa=class extends na{pre_tokenize_text(e){return Bi(e)}},pa=class extends na{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;nthis.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},va=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,new Map)}},ya=class{constructor(){this.root=va.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=va.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let n=``;for(let r of e){if(n+=r,t=t.children.get(r),t===void 0)return;t.is_leaf&&(yield n)}}},ba=class e{constructor(e,t,n,r,i){this.token_id=e,this.node_id=t,this.pos=n,this.length=r,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},xa=class{constructor(e,t,n){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new ba(this.bos_token_id??0,0,0,0,0),i=new ba(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=this.nodes.length,a=new ba(r,i,e,t,n);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function Sa(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r[e,t])),this.bos_token=` `,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=Sa(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new ya,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;ne>t,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),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){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},Ea=class extends ga{constructor(e){super(e),this.tokens_to_ids=Ii(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;this.merges=Array.isArray(e.merges[0])?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),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.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new Ta(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new wa((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},Da=class extends ga{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=Ii(t.target_lang?n[t.target_lang]:n),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=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function Oa(e,t){switch(e.type){case`WordPiece`:return new _a(e);case`Unigram`:return new Ca(e,t.eos_token);case`BPE`:return new Ea(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Ca(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new Ea(e):new _a(e):new Da(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var ka=Oa,Aa=class extends Vi{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},ja=class extends Aa{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=Fi(i,e),a=Fi(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=Fi(i,t),a=Fi(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},Ma=class extends Aa{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},Na=class extends Aa{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=Fi([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=Fi(e,i,t,a),r=Fi(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Pa=class extends Aa{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=Fi([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=Fi(e,i,t,a),r=Fi(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Fa=class extends Aa{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>La(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function Ia(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new ja(e);case`ByteLevel`:return new Ma(e);case`BertProcessing`:return new Na(e);case`RobertaProcessing`:return new Pa(e);case`Sequence`:return new Fa(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var La=Ia,Ra=class extends Vi{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=`trim_offsets`in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},za=class extends Ra{constructor(e){super(e),this.byte_decoder=Ci,this.text_decoder=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},Ba=class extends Ra{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=Di(e)),e})}},Va=class extends Ra{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;nt.replaceAll(this.suffix,n===e.length-1?``:` `))}},Ua=class extends Ra{constructor(e){super(e),this.pad_token=e.pad_token??``,this.word_delimiter_token=e.word_delimiter_token??``,this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return``;let t=[e[0]];for(let n=1;ne!==this.pad_token).join(``);return this.cleanup&&(n=Di(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Wa=class extends Ra{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>Xa(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},Ga=class extends Ra{decode_chain(e){let t=Oi(this.config.pattern),n=this.config.content??``;return t===null?e:e.map(e=>e.replaceAll(t,n))}},Ka=class extends Ra{decode_chain(e){return[e.join(``)]}},qa=class extends Ra{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function Ya(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new za(e);case`WordPiece`:return new Ba(e);case`Metaspace`:return new Va(e);case`BPEDecoder`:return new Ha(e);case`CTC`:return new Ua(e);case`Sequence`:return new Wa(e);case`Replace`:return new Ga(e);case`Fuse`:return new Ka(e);case`Strip`:return new qa(e);case`ByteFallback`:return new Ja(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var Xa=Ya,Za=class{constructor(e,t){let n=zi(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=zi(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=ta(this.tokenizer.normalizer),this.pre_tokenizer=ha(this.tokenizer.pre_tokenizer),this.model=ka(this.tokenizer.model,this.config),this.post_processor=La(this.tokenizer.post_processor),this.decoder=Xa(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=new Map;for(let e of this.tokenizer.added_tokens){let t=new xi(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new bi(i),this.splitter_normalized=new bi(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Mi(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Di(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=Pi(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:Fi(r??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let n=0;n=`,W.ComparisonBinaryOperator],[`==`,W.ComparisonBinaryOperator],[`!=`,W.ComparisonBinaryOperator],[`<`,W.ComparisonBinaryOperator],[`>`,W.ComparisonBinaryOperator],[`+`,W.AdditiveBinaryOperator],[`-`,W.AdditiveBinaryOperator],[`~`,W.AdditiveBinaryOperator],[`*`,W.MultiplicativeBinaryOperator],[`/`,W.MultiplicativeBinaryOperator],[`%`,W.MultiplicativeBinaryOperator],[`=`,W.Equals]],ro=new Map([[`n`,` +`],[`t`,` `],[`r`,`\r`],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`'`,`'`],[`"`,`"`],[`\\`,`\\`]]);function io(e,t={}){return e.endsWith(` +`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,`$1`)),e.replace(/{%\s*(end)?generation\s*%}/gs,``)}function ao(e,t={}){let n=[],r=io(e,t),i=0,a=0,o=e=>{let t=``;for(;e(r[i]);){if(r[i]===`\\`){if(++i,i>=r.length)throw SyntaxError(`Unexpected end of input`);let e=r[i++],n=ro.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n;continue}if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`)}return t},s=()=>{let e=n.at(-1);e&&e.type===W.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i0){n.push(new Qa(e,W.Text));continue}}if(r[i]===`{`&&r[i+1]===`#`){i+=2;let e=r[i]===`-`;e&&++i;let t=``;for(;r[i]!==`#`||r[i+1]!==`}`;){if(i+2>=r.length)throw SyntaxError(`Missing end of comment tag`);t+=r[i++]}let a=t.endsWith(`-`);a&&(t=t.slice(0,-1)),e&&s(),n.push(new Qa(t,W.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new Qa(`{%`,W.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new Qa(`{{`,W.OpenExpression)),a=0,i+=3;continue}if(o(to),r.slice(i,i+3)===`-%}`){n.push(new Qa(`%}`,W.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new Qa(`}}`,W.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===W.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case W.Identifier:case W.NumericLiteral:case W.StringLiteral:case W.CloseParen:case W.CloseSquareBracket:break;default:{++i;let e=o(eo);n.push(new Qa(`${t}${e}`,e.length>0?W.NumericLiteral:W.UnaryOperator));continue}}}for(let[e,t]of no)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new Qa(e,t)),t===W.OpenExpression?a=0:t===W.OpenCurlyBracket?++a:t===W.CloseCurlyBracket&&--a,i+=e.length;continue main}if(t===`'`||t===`"`){++i;let e=o(e=>e!==t);n.push(new Qa(e,W.StringLiteral)),++i;continue}if(eo(t)){let e=o(eo);if(r[i]===`.`&&eo(r[i+1])){++i;let t=o(eo);e=`${e}.${t}`}n.push(new Qa(e,W.NumericLiteral));continue}if($a(t)){let e=o($a);n.push(new Qa(e,W.Identifier));continue}throw SyntaxError(`Unexpected character: ${t}`)}return n}var oo=class{type=`Statement`},so=class extends oo{constructor(e){super(),this.body=e}type=`Program`},co=class extends oo{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},lo=class extends oo{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},uo=class extends oo{type=`Break`},fo=class extends oo{type=`Continue`},po=class extends oo{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},mo=class extends oo{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},ho=class extends oo{constructor(e){super(),this.value=e}type=`Comment`},go=class extends oo{type=`Expression`},_o=class extends go{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},vo=class extends go{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},yo=class extends go{constructor(e){super(),this.value=e}type=`Identifier`},bo=class extends go{constructor(e){super(),this.value=e}type=`Literal`},xo=class extends bo{type=`IntegerLiteral`},So=class extends bo{type=`FloatLiteral`},Co=class extends bo{type=`StringLiteral`},wo=class extends bo{type=`ArrayLiteral`},To=class extends bo{type=`TupleLiteral`},Eo=class extends bo{type=`ObjectLiteral`},Do=class extends go{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},Oo=class extends go{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},ko=class extends oo{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},Ao=class extends go{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},jo=class extends go{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},Mo=class extends go{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},No=class extends go{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},Po=class extends go{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},Fo=class extends go{constructor(e){super(),this.argument=e}type=`SpreadExpression`},Io=class extends oo{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},Lo=class extends go{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function Ro(e){let t=new so([]),n=0;function r(t,r){let i=e[n++];if(!i||i.type!==t)throw Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function i(e){if(!c(e))throw SyntaxError(`Expected ${e}`);++n}function a(){switch(e[n].type){case W.Comment:return new ho(e[n++].value);case W.Text:return l();case W.OpenStatement:return u();case W.OpenExpression:return d();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}function o(...t){return n+t.length<=e.length&&t.every((t,r)=>t===e[n+r].type)}function s(...t){return e[n]?.type===W.OpenStatement&&e[n+1]?.type===W.Identifier&&t.includes(e[n+1]?.value)}function c(...t){return n+t.length<=e.length&&t.every((t,r)=>e[n+r].type===`Identifier`&&t===e[n+r].value)}function l(){return new Co(r(W.Text,`Expected text token`).value)}function u(){if(r(W.OpenStatement,`Expected opening statement token`),e[n].type!==W.Identifier)throw SyntaxError(`Unknown statement, got ${e[n].type}`);let t=e[n].value,c;switch(t){case`set`:++n,c=f();break;case`if`:++n,c=p(),r(W.OpenStatement,`Expected {% token`),i(`endif`),r(W.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(W.OpenStatement,`Expected {% token`),i(`endmacro`),r(W.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(W.OpenStatement,`Expected {% token`),i(`endfor`),r(W.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(W.OpenParen)&&(e=E());let t=N();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=E();r(W.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(W.OpenStatement,`Expected '{%'`),i(`endcall`),r(W.CloseStatement,`Expected closing statement token`),c=new Io(new vo(t,l),e,u);break}case`break`:++n,r(W.CloseStatement,`Expected closing statement token`),c=new uo;break;case`continue`:++n,r(W.CloseStatement,`Expected closing statement token`),c=new fo;break;case`filter`:{++n;let e=N();e instanceof yo&&o(W.OpenParen)&&(e=T(e)),r(W.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(W.OpenStatement,`Expected '{%'`),i(`endfilter`),r(W.CloseStatement,`Expected '%}'`),c=new ko(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(W.OpenExpression,`Expected opening expression token`);let e=_();return r(W.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(W.Equals))++n,t=h();else{for(r(W.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(W.OpenStatement,`Expected {% token`),i(`endset`)}return r(W.CloseStatement,`Expected closing statement token`),new po(e,t,c)}function p(){let e=_();r(W.CloseStatement,`Expected closing statement token`);let t=[],i=[];for(;!s(`elif`,`else`,`endif`);)t.push(a());if(s(`elif`)){++n,++n;let e=p();i.push(e)}else if(s(`else`))for(++n,++n,r(W.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new co(e,t,i)}function m(){let e=N();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=E();r(W.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new mo(e,t,n)}function h(e=!1){let t=e?N:_,r=[t()],i=o(W.Comma);for(;i&&(++n,r.push(t()),o(W.Comma)););return i?new To(r):r[0]}function g(){let e=h(!0);if(!(e instanceof yo||e instanceof To))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!c(`in`))throw SyntaxError("Expected `in` keyword following loop variable");++n;let t=_();r(W.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(W.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new lo(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new Lo(t,e,v())):new Ao(e,t)}return e}function y(){let t=b();for(;c(`or`);){let r=e[n];++n;let i=b();t=new Do(r,t,i)}return t}function b(){let t=x();for(;c(`and`);){let r=e[n];++n;let i=x();t=new Do(r,t,i)}return t}function x(){let t;for(;c(`not`);){let r=e[n];++n,t=new Mo(r,x())}return t??S()}function S(){let t=C();for(;;){let r;if(c(`not`,`in`))r=new Qa(`not in`,W.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(W.ComparisonBinaryOperator))r=e[n++];else break;let i=C();t=new Do(r,t,i)}return t}function C(){let t=A();for(;o(W.AdditiveBinaryOperator);){let r=e[n];++n;let i=A();t=new Do(r,t,i)}return t}function w(){let e=k(N());return o(W.OpenParen)?T(e):e}function T(e){let t=new vo(e,E());return t=k(t),o(W.OpenParen)&&(t=T(t)),t}function E(){r(W.OpenParen,`Expected opening parenthesis for arguments list`);let e=D();return r(W.CloseParen,`Expected closing parenthesis for arguments list`),e}function D(){let t=[];for(;!o(W.CloseParen);){let r;if(e[n].type===W.MultiplicativeBinaryOperator&&e[n].value===`*`)++n,r=new Fo(_());else if(r=_(),o(W.Equals)){if(++n,!(r instanceof yo))throw SyntaxError(`Expected identifier for keyword argument`);let e=_();r=new Po(r,e)}t.push(r),o(W.Comma)&&++n}return t}function O(){let e=[],t=!1;for(;!o(W.CloseSquareBracket);)o(W.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(W.Colon)&&(++n,t=!0));if(e.length===0)throw SyntaxError(`Expected at least one argument for member/slice expression`);if(t){if(e.length>3)throw SyntaxError(`Expected 0-3 arguments for slice expression`);return new No(...e)}return e[0]}function k(t){for(;o(W.Dot)||o(W.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===W.OpenSquareBracket;if(o)a=O(),r(W.CloseSquareBracket,`Expected closing square bracket`);else if(a=N(),a.type!==`Identifier`)throw SyntaxError(`Expected identifier following dot operator`);t=new _o(t,a,o)}return t}function A(){let t=j();for(;o(W.MultiplicativeBinaryOperator);){let r=e[n++],i=j();t=new Do(r,t,i)}return t}function j(){let e=M();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=N();if(!(r instanceof yo))throw SyntaxError(`Expected identifier for the test`);e=new jo(e,t,r)}return e}function M(){let e=w();for(;o(W.Pipe);){++n;let t=N();if(!(t instanceof yo))throw SyntaxError(`Expected identifier for the filter`);o(W.OpenParen)&&(t=T(t)),e=new Oo(e,t)}return e}function N(){let t=e[n++];switch(t.type){case W.NumericLiteral:{let e=t.value;return e.includes(`.`)?new So(Number(e)):new xo(Number(e))}case W.StringLiteral:{let r=t.value;for(;o(W.StringLiteral);)r+=e[n++].value;return new Co(r)}case W.Identifier:return new yo(t.value);case W.OpenParen:{let e=h();return r(W.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),e}case W.OpenSquareBracket:{let e=[];for(;!o(W.CloseSquareBracket);)e.push(_()),o(W.Comma)&&++n;return++n,new wo(e)}case W.OpenCurlyBracket:{let e=new Map;for(;!o(W.CloseCurlyBracket);){let t=_();r(W.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(W.Comma)&&++n}return++n,new Eo(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n0)for(let i=e;it;i+=n)r.push(i);return r}function Bo(e,t,n,r=1){let i=Math.sign(r);i>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let a=[];for(let o=t;i*oe.toUpperCase())}function Ho(e){return Uo(new Date,e)}function Uo(e,t){let n=new Intl.DateTimeFormat(void 0,{month:`long`}),r=new Intl.DateTimeFormat(void 0,{month:`short`}),i=e=>e<10?`0`+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case`%Y`:return e.getFullYear().toString();case`%m`:return i(e.getMonth()+1);case`%d`:return i(e.getDate());case`%b`:return r.format(e);case`%B`:return n.format(e);case`%H`:return i(e.getHours());case`%M`:return i(e.getMinutes());case`%%`:return`%`;default:return t}})}function Wo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Go(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?RegExp(`(?=)`,`gu`):new RegExp(Wo(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var Ko=class extends Error{},qo=class extends Error{},Jo=class{type=`RuntimeValue`;value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new K(!!this.value)}toString(){return String(this.value)}},Yo=class extends Jo{type=`IntegerValue`},Xo=class extends Jo{type=`FloatValue`;toString(){return this.value%1==0?this.value.toFixed(1):this.value.toString()}},G=class extends Jo{type=`StringValue`;builtins=new Map([[`upper`,new is(()=>new G(this.value.toUpperCase()))],[`lower`,new is(()=>new G(this.value.toLowerCase()))],[`strip`,new is(()=>new G(this.value.trim()))],[`title`,new is(()=>new G(Vo(this.value)))],[`capitalize`,new is(()=>new G(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new Yo(this.value.length)],[`rstrip`,new is(()=>new G(this.value.trimEnd()))],[`lstrip`,new is(()=>new G(this.value.trimStart()))],[`startswith`,new is(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof G)return new K(this.value.startsWith(t.value));if(t instanceof ns){for(let e of t.value){if(!(e instanceof G))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new K(!0)}return new K(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new is(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof G)return new K(this.value.endsWith(t.value));if(t instanceof ns){for(let e of t.value){if(!(e instanceof G))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new K(!0)}return new K(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new is(e=>{let t=e[0]??new as;if(!(t instanceof G||t instanceof as))throw Error(`sep argument must be a string or null`);let n=e[1]??new Yo(-1);if(!(n instanceof Yo))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof as){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new ns(r.map(e=>new G(e)))})],[`replace`,new is(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof G&&n instanceof G))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new as:e[2]:new as,!(r instanceof Yo||r instanceof as))throw Error(`replace() count argument must be a number or null`);return new G(Go(this.value,t.value,n.value,r.value))})]])},K=class extends Jo{type=`BooleanValue`},Zo=/[\x7f-\uffff]/g;function Qo(e){return e.replace(Zo,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function $o(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=Qo(t)),t}case`ArrayValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=` +`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>$o(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}else{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=Qo(s));let c=`${s}${l}${$o(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var es=class extends Jo{type=`ObjectValue`;__bool__(){return new K(this.value.size>0)}builtins=new Map([[`get`,new is(([e,t])=>{if(!(e instanceof G))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new as})],[`items`,new is(()=>this.items())],[`keys`,new is(()=>this.keys())],[`values`,new is(()=>this.values())],[`dictsort`,new is(e=>{let t=new Map,n=e.filter(e=>e instanceof ts?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new K(!1);if(!(r instanceof K))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new G(`key`);if(!(i instanceof G))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new K(!1);if(!(a instanceof K))throw Error(`reverse must be a boolean`);return new ns(Array.from(this.value.entries()).map(([e,t])=>new ns([new G(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=us(o,s,r.value);return a.value?-c:c}))})]]);items(){return new ns(Array.from(this.value.entries()).map(([e,t])=>new ns([new G(e),t])))}keys(){return new ns(Array.from(this.value.keys()).map(e=>new G(e)))}values(){return new ns(Array.from(this.value.values()))}toString(){return $o(this,{},0,!1)}},ts=class extends es{type=`KeywordArgumentsValue`},ns=class extends Jo{type=`ArrayValue`;builtins=new Map([[`length`,new Yo(this.value.length)]]);__bool__(){return new K(this.value.length>0)}toString(){return $o(this,{},0,!1)}},rs=class extends ns{type=`TupleValue`},is=class extends Jo{type=`FunctionValue`},as=class extends Jo{type=`NullValue`},os=class extends Jo{type=`UndefinedValue`},ss=class{constructor(e){this.parent=e}variables=new Map([[`namespace`,new is(e=>{if(e.length===0)return new es(new Map);if(e.length!==1||!(e[0]instanceof es))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof is],[`odd`,e=>{if(!(e instanceof Yo))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof Yo))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof Yo||e instanceof Xo],[`integer`,e=>e instanceof Yo],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof es],[`sequence`,e=>e instanceof ns||e instanceof es||e instanceof G],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,fs(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new os}catch{return new os}}};function cs(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,zo),e.set(`strftime_now`,Ho),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function ls(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r instanceof es)r=r.value.get(e)??new os;else if(r instanceof ns){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&te instanceof Yo||e instanceof Xo||e instanceof K,i=e=>e instanceof K?+!!e.value:e.value;if(r(e)&&r(t)){let n=i(e),r=i(t);return nr)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),ri)}default:throw Error(`Cannot compare type: ${e.type}`)}}var ds=class{global;constructor(e){this.global=e??new ss}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t);switch(e.operator.value){case`and`:return n.__bool__().value?this.evaluate(e.right,t):n;case`or`:return n.__bool__().value?n:this.evaluate(e.right,t)}let r=this.evaluate(e.right,t);switch(e.operator.value){case`==`:return new K(n.value==r.value);case`!=`:return new K(n.value!=r.value)}if(n instanceof os||r instanceof os){if(r instanceof os&&[`in`,`not in`].includes(e.operator.value))return new K(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else if(n instanceof as||r instanceof as)throw Error(`Cannot perform operation on null values`);else if(e.operator.value===`~`)return new G(n.value.toString()+r.value.toString());else if((n instanceof Yo||n instanceof Xo)&&(r instanceof Yo||r instanceof Xo)){let t=n.value,i=r.value;switch(e.operator.value){case`+`:case`-`:case`*`:{let a=e.operator.value===`+`?t+i:e.operator.value===`-`?t-i:t*i;return n instanceof Xo||r instanceof Xo?new Xo(a):new Yo(a)}case`/`:return new Xo(t/i);case`%`:{let e=t%i;return n instanceof Xo||r instanceof Xo?new Xo(e):new Yo(e)}case`<`:return new K(t`:return new K(t>i);case`>=`:return new K(t>=i);case`<=`:return new K(t<=i)}}else if(n instanceof ns&&r instanceof ns)switch(e.operator.value){case`+`:return new ns(n.value.concat(r.value))}else if(r instanceof ns){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new K(t);case`not in`:return new K(!t)}}if(n instanceof G||r instanceof G)switch(e.operator.value){case`+`:return new G(n.value.toString()+r.value.toString())}if(n instanceof G&&r instanceof G)switch(e.operator.value){case`in`:return new K(r.value.includes(n.value));case`not in`:return new K(!r.value.includes(n.value))}if(n instanceof G&&r instanceof es)switch(e.operator.value){case`in`:return new K(r.value.has(n.value));case`not in`:return new K(!r.value.has(n.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=new Map;for(let i of e)if(i.type===`SpreadExpression`){let e=i,r=this.evaluate(e.argument,t);if(!(r instanceof ns))throw Error(`Cannot unpack non-iterable type: ${r.type}`);for(let e of r.value)n.push(e)}else if(i.type===`KeywordArgumentExpression`){let e=i;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw Error(`Positional arguments must come before keyword arguments`);n.push(this.evaluate(i,t))}return[n,r]}applyFilter(e,t,n){if(t.type===`Identifier`){let r=t;if(r.value===`safe`)return e;if(r.value===`tojson`)return new G($o(e,{}));if(e instanceof ns)switch(r.value){case`list`:return e;case`first`:return e.value[0];case`last`:return e.value[e.value.length-1];case`length`:return new Yo(e.value.length);case`reverse`:return new ns(e.value.slice().reverse());case`sort`:return new ns(e.value.slice().sort((e,t)=>us(e,t,!1)));case`join`:return new G(e.value.map(e=>e.value).join(``));case`string`:return new G($o(e,{},0,!1));case`unique`:{let t=new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new ns(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof G)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof is)return t.value([],n);if(t instanceof Yo)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new G(e.value.trim());case`indent`:return new G(e.value.split(` +`).map((e,t)=>t===0||e.length===0?e:` `+e).join(` +`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new Yo(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new Xo(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof Yo||e instanceof Xo)switch(r.value){case`abs`:return e instanceof Yo?new Yo(Math.abs(e.value)):new Xo(Math.abs(e.value));case`int`:return new Yo(Math.floor(e.value));case`float`:return new Xo(e.value);case`string`:return new G(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof es)switch(r.value){case`items`:return new ns(Array.from(e.value.entries()).map(([e,t])=>new ns([new G(e),t])));case`length`:return new Yo(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof is?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof K)switch(r.value){case`bool`:return new K(e.value);case`int`:return new Yo(+!!e.value);case`float`:return new Xo(+!!e.value);case`string`:return new G(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}else if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new as;if(!(i instanceof Yo||i instanceof as))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new K(!1);if(!(a instanceof K))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new K(!1);if(!(o instanceof K))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new as,c=null;if(s instanceof ns||s instanceof rs){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof G)||!(t instanceof G))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof as))throw Error(`If set, separators must be a tuple of two strings`);return new G($o(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}else if(i===`join`){let t;if(e instanceof G)t=Array.from(e.value);else if(e instanceof ns)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new G(``);if(!(s instanceof G))throw Error(`separator must be a string`);return new G(t.join(s.value))}else if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new Yo(0):new Xo(0));if(e instanceof G){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new Yo(t):new Xo(t)}else if(e instanceof Yo||e instanceof Xo)return e;else if(e instanceof K)return i===`int`?new Yo(+!!e.value):new Xo(+!!e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}else if(i===`default`){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new G(``),o=t[1]??i.get(`boolean`)??new K(!1);if(!(o instanceof K))throw Error("`default` filter flag must be a boolean");return e instanceof os||o.value&&!e.__bool__().value?a:e}if(e instanceof ns){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new K(!1);if(!(a instanceof K))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new K(!1);if(!(o instanceof K))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new as;if(!(s instanceof G||s instanceof Yo||s instanceof as))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof as?e:ls(e,s instanceof Yo?String(s.value):s.value);return new ns(e.value.slice().sort((e,t)=>{let n=us(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!(e instanceof es)))throw Error(`\`${i}\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \`${i}\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new ns(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof G))throw Error(`attribute must be a string`);let r=t.get(`default`);return new ns(e.value.map(e=>{if(!(e instanceof es))throw Error(`items in map must be an object`);let t=ls(e,n.value);return t instanceof os?r??new os:t}))}else throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${i}`)}else if(e instanceof G){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new Yo(4);if(!(a instanceof Yo))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new K(!1),s=t.at(2)??i.get(`blank`)??new K(!1),c=e.value.split(` +`),l=` `.repeat(a.value);return new G(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(` +`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof is))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new ts(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}else if(e instanceof es){let t=e.builtins.get(i);if(t&&t instanceof is){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new ts(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new K(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new os}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new K(!n.value);default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new G(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new ts(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof ns||e instanceof G))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof Yo||r instanceof os))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof Yo||i instanceof os))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof Yo||a instanceof os))throw Error(`Slice step must be numeric or undefined`);return e instanceof ns?new ns(Bo(e.value,r.value,i.value,a.value)):new G(Bo(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new G(e.property.value);let i;if(n instanceof es){if(!(r instanceof G))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof ns||n instanceof G)if(r instanceof Yo)i=n.value.at(r.value),n instanceof G&&(i=new G(n.value.at(r.value)));else if(r instanceof G)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof G))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof Jo?i:new os}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof ns))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;et.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r0?a[t-1]:new os],[`nextitem`,t{let r=new ss(n);t=t.slice();let i;t.at(-1)?.type===`KeywordArgumentsValue`&&(i=t.pop());for(let n=0;n{let r=new ss(n);if(e.callerArgs)for(let n=0;nthis.evaluate(e,t)));case`TupleLiteral`:return new rs(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof G))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new es(n)}case`Identifier`:return this.evaluateIdentifier(e,t);case`CallExpression`:return this.evaluateCallExpression(e,t);case`MemberExpression`:return this.evaluateMemberExpression(e,t);case`UnaryExpression`:return this.evaluateUnaryExpression(e,t);case`BinaryExpression`:return this.evaluateBinaryExpression(e,t);case`FilterExpression`:return this.evaluateFilterExpression(e,t);case`FilterStatement`:return this.evaluateFilterStatement(e,t);case`TestExpression`:return this.evaluateTestExpression(e,t);case`SelectExpression`:return this.evaluateSelectExpression(e,t);case`Ternary`:return this.evaluateTernaryExpression(e,t);case`Comment`:return new as;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function fs(e){switch(typeof e){case`number`:return Number.isInteger(e)?new Yo(e):new Xo(e);case`string`:return new G(e);case`boolean`:return new K(e);case`undefined`:return new os;case`object`:return e===null?new as:Array.isArray(e)?new ns(e.map(fs)):new es(new Map(Object.entries(e).map(([e,t])=>[e,fs(t)])));case`function`:return new is((t,n)=>fs(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var ps=` +`,ms=`{%- `,hs=` -%}`;function gs(e){switch(e.operator.type){case`MultiplicativeBinaryOperator`:return 4;case`AdditiveBinaryOperator`:return 3;case`ComparisonBinaryOperator`:return 2;case`Identifier`:return e.operator.value===`and`?1:e.operator.value===`in`||e.operator.value===`not in`?2:0}return 0}function _s(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return ys(e.body,0,n).replace(/\n$/,``)}function vs(...e){return ms+e.join(` `)+hs}function ys(e,t,n){return e.map(e=>bs(e,t,n)).join(ps)}function bs(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return ys(e.body,t,n);case`If`:return xs(e,t,n);case`For`:return Ss(e,t,n);case`Set`:return Cs(e,t,n);case`Macro`:return ws(e,t,n);case`Break`:return r+vs(`break`);case`Continue`:return r+vs(`continue`);case`CallStatement`:return Ts(e,t,n);case`FilterStatement`:return Es(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+Ds(e)+` -}}`}}function xs(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+vs(`if`,Ds(i[0].test))+ps+ys(i[0].body,t+1,n);for(let e=1;e0&&(o+=ps+r+vs(`else`)+ps+ys(a.alternate,t+1,n)),o+=ps+r+vs(`endif`),o}function Ss(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${Ds(t.lhs)} if ${Ds(t.test)}`}else i=Ds(e.iterable);let a=r+vs(`for`,Ds(e.loopvar),`in`,i)+ps+ys(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=ps+r+vs(`else`)+ps+ys(e.defaultBlock,t+1,n)),a+=ps+r+vs(`endfor`),a}function Cs(e,t,n){let r=n.repeat(t),i=Ds(e.assignee),a=e.value?Ds(e.value):``,o=r+vs(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+ps+ys(e.body,t+1,n)+ps+r+vs(`endset`)}function ws(e,t,n){let r=n.repeat(t),i=e.args.map(Ds).join(`, `);return r+vs(`macro`,`${e.name.value}(${i})`)+ps+ys(e.body,t+1,n)+ps+r+vs(`endmacro`)}function Ts(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(Ds).join(`, `)})`:``,a=Ds(e.call),o=r+vs(`call${i}`,a)+ps;return o+=ys(e.body,t+1,n)+ps,o+=r+vs(`endcall`),o}function Es(e,t,n){let r=n.repeat(t),i=r+vs(`filter`,e.filter.type===`Identifier`?e.filter.value:Ds(e.filter))+ps;return i+=ys(e.body,t+1,n)+ps,i+=r+vs(`endfilter`),i}function Ds(e,t=-1){switch(e.type){case`SpreadExpression`:return`*${Ds(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:return`${e.value}`;case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let n=e,r=gs(n),i=Ds(n.left,r),a=Ds(n.right,r+1),o=`${i} ${n.operator.value} ${a}`;return r`${Ds(e)}: ${Ds(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?Ds(t.start):``}:${t.stop?Ds(t.stop):``}${t.step?`:${Ds(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${Ds(t.value)}`}case`Ternary`:{let n=e,r=`${Ds(n.trueExpr)} if ${Ds(n.condition,0)} else ${Ds(n.falseExpr)}`;return t>-1?`(${r})`:r}default:throw Error(`Unknown expression type: ${e.type}`)}}var Os=class{parsed;constructor(e){this.parsed=Ro(ao(e,{lstrip_blocks:!0,trim_blocks:!0}))}render(e){let t=new ss;if(cs(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new ds(t).run(this.parsed).value}format(e){return _s(this.parsed,e?.indent||` `)}},ks={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`},As=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=jr.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=jr.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=jr.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,ks[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await jr.promises.readFile(this.filePath)).buffer}async blob(){let e=await jr.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await jr.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},js=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(Qr.IS_CRYPTO_AVAILABLE){let t=new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0;let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t&4294967295);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(1812433253,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1566083941))-i>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&2147483648|e[(t+1)%624]&2147483647;e[t]=(e[(t+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[Ms(this._random_fn,t)]}};function Ms(e,t){let n=0;for(let e=0;eMs(Ps.random,e),Is=new js,Ls=class{constructor(e){this.path=e}async match(e){let t=new As(Mr.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=Mr.join(this.path,e),i=r+`.tmp.${Qr.IS_PROCESS_AVAILABLE?process.pid:Date.now()}.${Is._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await jr.promises.mkdir(Mr.dirname(r),{recursive:!0});let s=jr.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{if(t){n(t);return}e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await jr.promises.rename(i,r)}catch(e){try{await jr.promises.unlink(i)}catch{}throw e}}async delete(e){let t=Mr.join(this.path,e);try{return await jr.promises.unlink(t),!0}catch{return!1}}},Rs={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`},zs=100,Bs=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Vs(...e){return e=e.map((t,n)=>(n&&(t=t.replace(RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(RegExp(`/$`),``)),t)),e.join(`/`)}function Hs(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function Us(e){return!(!Bs.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function Ws(e,t,n){if(!n)return null;let r=Rs[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}async function Gs(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&V.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function Ks(e){return Hs(e,[`blob:`])}function qs(e){let t;if(typeof location<`u`&&location.href)t=location.href;else if(import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var Js=`SHA-256`,Ys=`experimental_transformers-hash-cache`,Xs=e=>({algorithm:Js,value:e}),Zs=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Ys),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let[e]=await navigator.crossOriginStorage.requestFileHandles([Xs(t)]),n=await e.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let[n]=await navigator.crossOriginStorage.requestFileHandles([Xs(t)],{create:!0}),r=await n.createWritable();await r.write(e),await r.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(Js,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function Qs(e=null){let t=null;if(si.useCustomCache){if(!si.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!si.customCache.match||!si.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=si.customCache}if(!t&&si.experimental_useCrossOriginStorage&&Zs.isAvailable()&&(t=new Zs),!t&&si.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(si.cacheKey)}catch(e){V.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&si.useFSCache){if(!Qr.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new Ls(e??si.cacheDir)}return t}async function $s(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var ec=new class{#e;#t;constructor(e){this.#e=e,this.#t=new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function tc(e,t){let n=ec.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(ec.delete(e),Promise.reject(t)));return ec.put(e,r),r}async function nc(e){if(!Hs(e,[`http:`,`https:`]))return null;let t=oc(e);return t.set(`Range`,`bytes=0-0`),si.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function rc(e,t,n={}){return tc(JSON.stringify([e,t,n?.revision,n?.cache_dir,n?.local_files_only]),()=>ic(e,t,n))}async function ic(e,t,n){let r=await Qs(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=sc(e,t,n,r),c=await cc(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(si.allowLocalModels&&!Hs(i,[`http:`,`https:`]))try{let e=await ac(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(si.allowRemoteModels&&!n.local_files_only&&s)try{let e=await nc(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \d+-\d+\/(\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}}catch(e){V.warn(`Unable to fetch file metadata for "${a}": ${e}`)}return{exists:!1,fromCache:!1}}async function ac(e){return si.useFS&&!Hs(e,[`http:`,`https:`,`blob:`])?new As(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):si.fetch(e,{headers:oc(e)})}function oc(e){let t=typeof process<`u`&&process?.release?.name===`node`,n=new Headers;if(t){let t=!!{}?.TESTING_REMOTELY,r=si.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),Hs(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e={}?.HF_TOKEN??{}?.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function sc(e,t,n={},r=null){let i=n.revision??`main`,a=Vs(e,t),o=Us(e),s=o?Vs(si.localModelPath,a):a,c=Vs(si.remoteHost,si.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof Ls?i===`main`?a:Vs(e,i,t):c,validModelId:o}}async function cc(e,t,n){if(e)return await $s(e,t,n)}async function lc(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0){if(!a){let a=o.progress_callback?n=>ui(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}else if(typeof i!=`string`){let e=new Headers(i.headers);e.set(`content-length`,a.byteLength.toString()),await n.put(r,new Response(a,{headers:e})).catch(e=>{V.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function uc(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=sc(e,t,r,a),d,f=!1,p;p=await cc(a,s,l);let m=p!==void 0;if(m)d=l;else{if(si.allowLocalModels){if(!Hs(o,[`http:`,`https:`]))try{p=await ac(s),d=s}catch(e){V.warn(`Unable to load from local path "${s}": "${e}"`)}else if(r.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);else if(!si.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!si.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${s}".`);return null}if(!u)throw Error(`Local file missing at "${s}" and download aborted due to invalid model ID "${e}".`);if(p=await ac(c),p.status!==200)return Ws(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}ui(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(Qr.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`)if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),ui(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await rc(e,t,r);n.size&&(i=n.size)}catch{}n=await Gs(p,n=>{ui(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}h=n}if(f&&d&&typeof p!=`string`&&await lc(e,t,a,d,p,h,r),Qr.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;ui(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(ui(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!Qr.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof As)return p.filePath;let g=await a?.match(d);if(g instanceof As)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}var dc=new Map;async function fc(e,t,n=!0,r={},i=!1){if(!si.allowLocalModels){if(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`).");if(!si.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}ui(r.progress_callback,{status:`initiate`,name:e,file:t});let a=`${e}::${t}`,o=dc.get(a);return o||(o=uc(e,t,n,r,i,await Qs(r?.cache_dir)).then(e=>(dc.delete(a),e),e=>{throw dc.delete(a),e}),dc.set(a,o)),await o}async function pc(e,t,n=!0,r={}){let i=await fc(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function mc(e,t,n=!0,r={}){let i=await pc(e,t,n,r);return i===null?{}:JSON.parse(i)}function hc(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function _c(e){let t=bc(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function vc(e){let t=bc(e)[0],n=0;for(let r=0;re-t-r)}function yc(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[t,n]}function xc(e){return e>0&&(e&e-1)==0}var Sc=class{constructor(e){if(this.size=e|0,this.size<=1||!xc(this.size))throw 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 e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o>>1,i>>>1)}else for(o=0,s=0;o>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o>>1;for(let t=2;t>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new Sc(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function Ec(e,t){let n=10**t;return Math.round(e*n)/n}function Dc(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function Oc(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var kc=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let t=new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t>10,s=t&1023;if(o===31)i=a|2139095040|s<<13;else if(o===0)if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;ejc});var jc={};async function Mc(e){let t=e.split(`/`).pop(),n;try{if(n=await Qs(),n){let t=await n.match(e);if(t)return t}}catch(e){V.warn(`Failed to load ${t} from cache:`,e)}let r=await si.fetch(e);if(!r.ok)throw Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(n)try{await n.put(e,r.clone())}catch(e){V.warn(`Failed to cache ${t}:`,e)}return r}async function Nc(e){let t=await Mc(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return V.warn(`Failed to read WASM binary:`,e),null}}async function Pc(e){if(Qr.IS_SERVICE_WORKER_ENV||Qr.IS_CHROME_AVAILABLE)return e;let t=await Mc(e);if(!t||typeof t==`string`)return null;try{let e=await t.text();e=e.replaceAll(`globalThis.process?.versions?.node`,`false`);let n=new Blob([e],{type:`text/javascript`});return URL.createObjectURL(n)}catch(e){return V.warn(`Failed to read WASM factory:`,e),null}}var Fc=Object.freeze({auto:null,gpu:null,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:{name:`webnn`,deviceType:`cpu`},"webnn-npu":{name:`webnn`,deviceType:`npu`},"webnn-gpu":{name:`webnn`,deviceType:`gpu`},"webnn-cpu":{name:`webnn`,deviceType:`cpu`}});function Ic(e){return e<=ai.DEBUG?0:e<=ai.INFO?2:e<=ai.WARNING||e<=ai.ERROR?3:4}var Lc={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},Rc=[],zc,Bc,Vc=Symbol.for(`onnxruntime`);if(Vc in globalThis)Bc=globalThis[Vc];else if(Qr.IS_NODE_ENV){switch(Bc=Ac,process.platform){case`win32`:Rc.push(`dml`);break;case`linux`:process.arch===`x64`&&Rc.push(`cuda`);break;case`darwin`:Rc.push(`coreml`);break}Rc.push(`webgpu`),Rc.push(`cpu`),zc=[`cpu`]}else Bc=v,Qr.IS_WEBNN_AVAILABLE&&Rc.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),Qr.IS_WEBGPU_AVAILABLE&&Rc.push(`webgpu`),Rc.push(`wasm`),zc=[`wasm`];var Hc=Bc.InferenceSession;function Uc(e=null){if(!e)return zc;switch(e){case`auto`:return Rc;case`gpu`:return Rc.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(Rc.includes(e))return[Fc[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${Rc.join(`, `)}.`)}var Wc=Promise.resolve(),Gc=null;async function Kc(){if(Gc)return Gc;if(!(si.useWasmCache&&typeof Zc?.wasm?.wasmPaths==`object`&&Zc?.wasm?.wasmPaths?.wasm&&Zc?.wasm?.wasmPaths?.mjs)){if(Qr.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return Gc=Promise.resolve(),Gc}return Gc=(async()=>{let e=Zc.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!Ks(e.wasm)?(async()=>{try{let n=await Nc(qs(e.wasm));n&&(Zc.wasm.wasmBinary=n,t=!0)}catch(e){V.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!Ks(e.mjs)?(async()=>{try{let t=await Pc(qs(e.mjs));t&&(Zc.wasm.wasmPaths.mjs=t)}catch(e){V.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(Zc.wasm.wasmPaths.mjs=e.mjs)})(),Gc}async function qc(e,t,n){await Kc();let r=Ic(si.logLevel??ai.WARNING),i=()=>Hc.create(e,{logSeverityLevel:r,...t}),a=await(Qr.IS_WEB_ENV?Wc=Wc.then(i):i());return a.config=n,a}var Jc=Promise.resolve();async function Yc(e,t){let n=()=>e.run(t);return Qr.IS_WEB_ENV?Jc=Jc.then(n):n()}function Xc(e){return e instanceof Bc.Tensor}var Zc=Bc?.env;function Qc(){return Zc?.wasm?.proxy}if(Zc){let e=function(e){Zc.logLevel=Lc[Ic(e)]};if(Zc.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&Zc.versions?.web&&!Zc.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Zc.versions.web}/dist/`;Zc.wasm.wasmPaths=Qr.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}Zc.wasm.proxy=!1}Zc.webgpu&&(Zc.webgpu.powerPreference=`high-performance`),e(si.logLevel??ai.WARNING),si.backends.onnx={...Zc,setLogLevel:e}}var $c=async(e,t,n)=>{let r=await qc(new Uint8Array(e),t);return(async e=>{let t=Qc(),i=await Yc(r,Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])));return Array.isArray(n)?n.map(e=>new q(i[e])):new q(i[n])})},el=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=$c([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,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,21],this.session_options,`y`),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||=$c([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||=$c([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||=$c([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||=$c([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||=$c([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||=$c([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}static get slice(){return this._slice||=$c([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,`y`),this._slice}},tl=Object.freeze({auto:`auto`,gpu:`gpu`,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:`webnn`,"webnn-npu":`webnn-npu`,"webnn-gpu":`webnn-gpu`,"webnn-cpu":`webnn-cpu`}),nl=Qr.IS_NODE_ENV?`cpu`:`wasm`;function rl(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for "${t}". Using the default device (${nl}).`),nl):nl}var il=(function(){let e;return async function(){if(e===void 0)if(!Qr.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}return e}})(),al=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`,q2:`q2`,q2f16:`q2f16`,q1:`q1`,q1f16:`q1f16`}),ol=al.fp32,sl=Object.freeze({[tl.wasm]:al.q8}),cl=Object.freeze({[al.fp32]:``,[al.fp16]:`_fp16`,[al.int8]:`_int8`,[al.uint8]:`_uint8`,[al.q8]:`_quantized`,[al.q4]:`_q4`,[al.q2]:`_q2`,[al.q1]:`_q1`,[al.q4f16]:`_q4f16`,[al.q2f16]:`_q2f16`,[al.q1f16]:`_q1f16`,[al.bnb4]:`_bnb4`});function ll(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===al.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==al.auto&&al.hasOwnProperty(e))return e}s=sl[n]??ol}else s=a&&al.hasOwnProperty(a)?a:sl[n]??ol;return o&&i&&i(`dtype not specified for "${t}". Using the default dtype (${s}) for this device (${n}).`),s}var ul=Object.freeze({float32:Float32Array,float16:typeof Float16Array<`u`?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),q=class e{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 Xc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Or(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}else return new e(this.type,[this.data[t]],r)}indexOf(e){let t=this.data;for(let n=0;na)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return fl(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=Tl(o,this,n,r);if(t!==1)for(let e=0;e=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return Ol(this.dims)}squeeze(t=null){return new e(this.type,this.data,bl(this.dims,t))}squeeze_(e=null){return this.dims=bl(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,xl(this.dims,t))}unsqueeze_(e){return this.dims=xl(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;er===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;tt);return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;eMath.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=bc(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=Tl((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=yc(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=bc(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.lengthe===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=Ol(r),l=Ol(i);for(let e=0;eBigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,kc(this.data),this.dims);return new e(t,ul[t].from(this.data,n),this.dims)}};function dl(e,t){let n=e.length;if(n!==t.reduce((e,t)=>e*t))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.lengthnew q(`int64`,e,[e.length]);async function vl(e,t,n,r,i){return await(await el.slice)({x:e,s:_l(t),e:_l(n),a:_l(r),t:_l(i??Array(r.length).fill(1))})}function yl(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;ee!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function xl(e,t){return t=Sl(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Sl(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Cl(e,t=0){t=Sl(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new q(a,i,n)}function wl(e,t=0){return Cl(e.map(e=>e.unsqueeze(t)),t)}function Tl(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=Sl(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function El(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new q(e.type,[t],[]);return[new q(e.type,[r],[]),a]}t=Sl(t,a.length);let o=Dl(e,t,r),s=o.data,[c,l,u]=Tl((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;ee+t,0);return new q(e.type,[t/i.length],[])}t=Sl(t,r.length);let[a,o,s]=Tl((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e=0;--n)t[n]=r,r*=e[n];return t}function kl(e,t,n,r){return new q(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function Al(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return kl(e,t,n,r)}function jl(e,t){return Al(e.dims,t)}function Ml(e){return kl(e,1n,`int64`,BigInt64Array)}function Nl(e){return Ml(e.dims)}function Pl(e){return kl(e,0n,`int64`,BigInt64Array)}function Fl(e){return Pl(e.dims)}function Il(e){let t=e.reduce((e,t)=>e*t,1);return new q(`float32`,Float32Array.from({length:t},()=>Ps.gauss()),e)}function Ll(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e0),r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new q(r,o,[e.dims[0],e.dims[1]/8])}async function Rl(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await rc(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function zl(e,t){let n=await Rl(e);return await Promise.all(n.map(n=>mc(e,n,!0,t)))}function Bl(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Vl=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function Hl(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?hi(e[i],s):hi(s,e[i])}}function Ul(e,t){for(let n of Object.keys(e))e[n].length=t}function Wl(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t)if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}else return t}return null}function Gl(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var J=class extends li{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new Za(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Wl(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Wl(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Wl(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Wl(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Wl(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Wl(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with "name" and "template" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map;let n=Gl(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await zl(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let{text_pair:n=null,add_special_tokens:r=!0,padding:i=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:s=null}=t,c=t.return_tensor??!0,l=Array.isArray(e),u;if(l){if(e.length===0)throw Error(`text array must be non-empty`);if(n!==null){if(!Array.isArray(n))throw Error(`text_pair must also be an array`);if(e.length!==n.length)throw Error(`text and text_pair must have the same length`);u=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:a}))}else u=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:a})]}if(s===null?s=this.model_max_length:o===null&&(i===!0?(V.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),s=this.model_max_length):i===!1&&(V.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."),o=!0)),i===!0&&(s=Math.min(bc(u.map(e=>e.input_ids.length))[0],s??1/0)),s=Math.min(s,this.model_max_length??1/0),i||o)for(let e=0;es?o&&Ul(u[e],s):i&&Hl(u[e],s,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let d={};if(c){if(!(i&&o)&&u.some(e=>{for(let t of Object.keys(e))if(e[t].length!==u[0][t]?.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.`);let e=[u.length,u[0].input_ids.length];for(let t of Object.keys(u[0]))d[t]=new q(`int64`,BigInt64Array.from(u.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(u[0]))d[e]=u.map(t=>t[e]);if(!l)for(let e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof q&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof q&&(e=Bl(e)),!Array.isArray(e)||e.length===0||!fi(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:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null)if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=n.default;else 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(n).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`);return e}apply_chat_template(e,t={}){let{tools:n=null,documents:r=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:s=!1,truncation:c=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!0,tokenizer_kwargs:f={},...p}=t;if(i=this.get_chat_template({chat_template:i,tools:n}),typeof i!=`string`)throw Error(`chat_template must be a string, but got ${typeof i}`);let m=this._compiled_template_cache.get(i);m===void 0&&(m=new Os(i),this._compiled_template_cache.set(i,m));let h=Object.create(null);for(let e of Vl){let t=Wl(this.config,e);t&&(h[e]=t)}let g=m.render({messages:e,add_generation_prompt:a,tools:n,documents:r,...h,...p});if(o){let e=this._call(g,{add_special_tokens:!1,padding:s,truncation:c,max_length:l,return_tensor:u,...f});return d?e:e.input_ids}return g}};function Kl(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);for(let t of e._tokenizer.post_processor.config.single)if(`SpecialToken`in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(i);break}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var ql={};Ar(ql,{AlbertTokenizer:()=>Jl,AutoTokenizer:()=>Ku,BartTokenizer:()=>Yl,BertTokenizer:()=>Xl,BlenderbotSmallTokenizer:()=>Zl,BlenderbotTokenizer:()=>Ql,BloomTokenizer:()=>$l,CLIPTokenizer:()=>tu,CamembertTokenizer:()=>eu,CodeGenTokenizer:()=>ru,CodeLlamaTokenizer:()=>nu,CohereAsrTokenizer:()=>au,CohereTokenizer:()=>iu,ConvBertTokenizer:()=>ou,DebertaTokenizer:()=>cu,DebertaV2Tokenizer:()=>su,DistilBertTokenizer:()=>lu,ElectraTokenizer:()=>uu,EsmTokenizer:()=>du,FalconTokenizer:()=>fu,GPT2Tokenizer:()=>hu,GPTNeoXTokenizer:()=>mu,GemmaTokenizer:()=>pu,HerbertTokenizer:()=>gu,LlamaTokenizer:()=>_u,M2M100Tokenizer:()=>vu,MBart50Tokenizer:()=>xu,MBartTokenizer:()=>bu,MPNetTokenizer:()=>wu,MarianTokenizer:()=>yu,MgpstrTokenizer:()=>Su,MobileBertTokenizer:()=>Cu,NllbTokenizer:()=>Tu,NougatTokenizer:()=>Eu,PreTrainedTokenizer:()=>J,Qwen2Tokenizer:()=>Du,RoFormerTokenizer:()=>ku,RobertaTokenizer:()=>Ou,SiglipTokenizer:()=>Au,SpeechT5Tokenizer:()=>ju,SqueezeBertTokenizer:()=>Mu,T5Tokenizer:()=>Nu,TokenizersBackend:()=>J,VitsTokenizer:()=>Fu,Wav2Vec2CTCTokenizer:()=>Iu,WhisperTokenizer:()=>Uu,XLMRobertaTokenizer:()=>Wu,XLMTokenizer:()=>Gu});var Jl=class extends J{return_token_type_ids=!0},Yl=class extends J{},Xl=class extends J{return_token_type_ids=!0},Zl=class extends J{},Ql=class extends J{},$l=class extends J{},eu=class extends J{},tu=class extends J{},nu=class extends J{},ru=class extends J{},iu=class extends J{},au=class extends J{},ou=class extends J{return_token_type_ids=!0},su=class extends J{return_token_type_ids=!0},cu=class extends J{return_token_type_ids=!0},lu=class extends J{},uu=class extends J{return_token_type_ids=!0},du=class extends J{},fu=class extends J{},pu=class extends J{},mu=class extends J{},hu=class extends J{},gu=class extends J{return_token_type_ids=!0},_u=class extends J{padding_side=`left`},vu=class extends J{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Kl(this,e,t,n)}},yu=class extends J{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),V.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;let[t,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||V.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),hi([e],super._encode_text(t))}}},bu=class extends J{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Kl(this,e,t,n)}},xu=class extends bu{},Su=class extends J{},Cu=class extends J{return_token_type_ids=!0},wu=class extends J{},Tu=class extends J{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Kl(this,e,t,n)}},Eu=class extends J{},Du=class extends J{},Ou=class extends J{},ku=class extends J{return_token_type_ids=!0},Au=class extends J{},ju=class extends J{},Mu=class extends J{return_token_type_ids=!0},Nu=class extends J{},Pu=class extends Ra{decode_chain(e){let t=``;for(let n=1;n[t,e]),...[[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]]);function Bu(e){e=e.toLowerCase();let t=zu.get(e);if(t===void 0){let n=e.match(/^<\|([a-z]{2})\|>$/);if(n&&(e=n[1]),Ru.has(e))t=e;else{let t=e.length===2?Ru.keys():Ru.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var Vu=RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,`gu`),Hu=.1,Uu=class extends J{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r=d&&g<=f){let e=Ec((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g0&&l.timestamp[1]!==null))for(let e of l.words)e.timestamp[1]>l.timestamp[1]&&l.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=l.timestamp[1]);c.push(l),p=[],b=[],m=[],x=[],l=s()}}else if(b.push(g),o){let e=Ec(i[n]+u,2),t;if(n+10?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw 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.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e0,o=a?[]:null,s=a?t[0]:null;for(let c=1;ce===g[n]&&s[i+n][0]-Hu<=t[c][m+n][0]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);if(a&&u===0&&r>0){let e=s[r-1][0],n=t[c].findIndex(t=>t[0]>=e);v=n===-1?l.length:n}i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=Vu.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=hi(o[c],o[l]),s[l]=hi(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;le),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},Wu=class extends J{},Gu=class extends J{return_token_type_ids=!0;constructor(e,t){super(e,t),V.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Ku=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await zl(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=ql[c];return l||=(V.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),J),new l(o,s)}},qu=`https://github.com/huggingface/transformers.js/issues/new/choose`,Ju=`preprocessor_config.json`,Yu=Ju,Xu=`processor_config.json`,Zu=`chat_template.jinja`,Qu=class extends li{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?mc(e,Xu,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?pc(e,Zu,!0,t):null]);return new this(n,r,i)}},$u={};Ar($u,{ChatterboxProcessor:()=>qd,CohereAsrProcessor:()=>Yd,Florence2Processor:()=>Bp,Gemma3Processor:()=>Vp,Gemma3nProcessor:()=>Hp,Gemma4Processor:()=>Up,Glm46VProcessor:()=>Gp,GraniteSpeechProcessor:()=>Kp,GroundingDinoProcessor:()=>Jp,Idefics3Processor:()=>Qp,JinaCLIPProcessor:()=>em,Lfm2VlProcessor:()=>tm,LlavaProcessor:()=>nm,MgpstrProcessor:()=>im,MoonshineProcessor:()=>am,OwlViTProcessor:()=>om,PaliGemmaProcessor:()=>lm,Phi3VProcessor:()=>fm,PixtralProcessor:()=>pm,Processor:()=>Qu,PyAnnoteProcessor:()=>mm,Qwen2VLProcessor:()=>Wp,Qwen2_5_VLProcessor:()=>hm,Qwen3VLProcessor:()=>gm,Sam2Processor:()=>vm,Sam2VideoProcessor:()=>ym,SamProcessor:()=>_m,SmolVLMProcessor:()=>Qp,SpeechT5Processor:()=>bm,UltravoxProcessor:()=>xm,VLChatProcessor:()=>$p,VoxtralProcessor:()=>Em,VoxtralRealtimeProcessor:()=>Mm,Wav2Vec2Processor:()=>Nm,Wav2Vec2ProcessorWithLM:()=>Pm,WhisperProcessor:()=>Fm});var ed=class extends li{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await mc(e,Ju,!0,t);return new this(n)}};function td(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} 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.`)}var nd={};Ar(nd,{ASTFeatureExtractor:()=>Ed,ChatterboxFeatureExtractor:()=>Od,ClapFeatureExtractor:()=>kd,CohereAsrFeatureExtractor:()=>Md,DacFeatureExtractor:()=>Nd,EncodecFeatureExtractor:()=>Dd,FeatureExtractor:()=>ed,Gemma3nAudioFeatureExtractor:()=>Pd,Gemma4AudioFeatureExtractor:()=>Fd,GraniteSpeechFeatureExtractor:()=>Id,MoonshineFeatureExtractor:()=>Ld,ParakeetFeatureExtractor:()=>jd,PyAnnoteFeatureExtractor:()=>Rd,SeamlessM4TFeatureExtractor:()=>zd,SnacFeatureExtractor:()=>Bd,SpeechT5FeatureExtractor:()=>Vd,VoxtralRealtimeFeatureExtractor:()=>Wd,Wav2Vec2FeatureExtractor:()=>Hd,WeSpeakerFeatureExtractor:()=>Ud,WhisperFeatureExtractor:()=>Gd});var rd={fromWeb:()=>{}};async function id(e,t){if(Qr.IS_BROWSER_ENV){if(Qr.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(Qr.IS_FS_AVAILABLE){let n=t.stream();await(rd.fromWeb(n),jr.createWriteStream(e),void 0)}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function ad(e,t){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.");let n=await(await ac(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&V.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function dd(e,t=`htk`){let n=ud[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var fd={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function pd(e,t=`htk`){let n=fd[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function md(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;nArray(e.length));for(let t=0;te+r*n)}function gd(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or "slaney"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=hd(dd(n,o),dd(r,o),t+2),l=pd(c,o),u;if(s){let t=i/((e-1)*2);u=dd(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=hd(0,Math.floor(i/2),e);let d=md(u,l);if(a!==null&&a===`slaney`)for(let n=0;ni)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(T!==n)throw Error(`Length of the window (${T}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw 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(!u)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){let t=Math.floor(n/2);switch(s){case`reflect`:e=_d(e,t,t);break;case`constant`:{let n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}case`semicausal`:{let n=new e.constructor(e.length+t);n.set(e,t),e=n;break}default:throw Error(`pad_mode="${s}" not implemented yet.`)}}let E=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&EE?x&&(k=b):k=O=b);let A=new wc(i),j=new Float64Array(i),M=new Float64Array(A.outputBufferSize),N=new Float32Array(D*k);for(let i=0;i=1;--e)j[e]-=l*j[e-1];j[0]*=1-l}for(let e=0;ee**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);let s=new Float64Array(r),c=i?Math.floor((r-e)/2):0;return s.set(o,c),s}function Cd(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=new ArrayBuffer(44),i=new DataView(r);return wd(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),wd(i,8,`WAVE`),wd(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),wd(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer)],{type:`audio/wav`})}function wd(e,t,n){for(let r=0;re+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),Cd(e,this.sampling_rate)}async save(e){return id(e,this.toBlob())}},Ed=class extends ed{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=gd(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=Sd(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return xd(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){td(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t0)if(n===`rand_trunc`){let n=Math.floor(Ps.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${n}" not implemented`);else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;r=1;--n)e[n]-=t*e[n-1];return await xd(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:`log`,mel_floor:-1/0,pad_mode:`constant`,center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){td(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e1?n-1:1;for(let e=0;e=l){s.push(e.slice(c,l));break}let t=Math.max(c,c+a-o),n=Math.min(c+a,l),i;i=n<=t?c+a:this._find_split_point_energy(e,t,n,r),i=Math.max(c+1,Math.min(i,l)),s.push(e.slice(c,i)),c=i}return s}_find_split_point_energy(e,t,n,r){let i=n-t;if(i<=r)return Math.floor((t+n)/2);let a=1/0,o=t,s=i-r;for(let n=0;n<=s;n+=r){let i=0;for(let a=0;at&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=Al([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},Fd=class extends Pd{async _extract_fbank_features(e,t){let{frame_length:n,hop_length:r,fft_length:i}=this.config,a=Math.floor(n/2),o=Math.floor((e.length+a-(n+1))/r)+1;return xd(e,this.window,n,r,{fft_length:i,center:!0,pad_mode:`semicausal`,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,mel_floor_mode:`add`,remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){td(e,`Gemma4AudioFeatureExtractor`);let n=e.length,r=await super._call(e,t),{input_features:i}=r,[,a,o]=i.dims,{frame_length:s,hop_length:c}=this.config,l=Math.floor(s/2),u=s+1,d=new Uint8Array(n+l+(t.pad_to_multiple_of??128));d.fill(1,l,l+n);let f=new Uint8Array(a);for(let e=0;e({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},zd=class extends ed{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=gd(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=Sd(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),xd(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){td(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new q(a.type,n,[c,t]),i&&(o=new q(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;ne+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){td(e,`Wav2Vec2FeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let n=[1,t.length];return{input_values:new q(`float32`,t,n),attention_mask:new q(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},Ud=class extends ed{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=gd(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=Sd(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),xd(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){td(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;tr?(e.length>this.config.n_samples&&V.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`."),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},Kd=class{static async from_pretrained(e,t={}){let n=await mc(e,Ju,!0,t),r=n.feature_extractor_type,i=nd[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${qu}.`);return new i(n)}},qd=class extends Qu{static tokenizer_class=Ku;static feature_extractor_class=Kd;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},Jd=new Set([`ja`,`zh`]),Yd=class extends Qu{static tokenizer_class=Ku;static feature_extractor_class=Kd;static uses_processor_config=!0;get_decoder_prompt_ids(e=`en`){let t=[`▁`,`<|startofcontext|>`,`<|startoftranscript|>`,`<|emo:undefined|>`,`<|${e}|>`,`<|${e}|>`,`<|pnc|>`,`<|noitn|>`,`<|notimestamp|>`,`<|nodiarize|>`];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t=`en`){let n=e.filter(e=>e&&e.trim());if(n.length===0)return``;let r=Jd.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},Xd={},Zd,Qd,$d;if(Qr.IS_WEB_ENV)Zd=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},$d=self.createImageBitmap,Qd=self.ImageData;else if(Xd)$d=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new nf(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var ef={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},tf=new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),nf=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;if(typeof t==`string`||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!Qr.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await ac(e);if(t.status!==200)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(Qr.IS_WEB_ENV){let t=await $d(e),n=Zd(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}else{let t=Xd(await e.arrayBuffer());return await $d(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.transpose(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}else{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await $d(e)}}async toBlob(e=`image/png`,t=1){if(!Qr.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new q(`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 Error(`Unsupported channel format: ${e}`);return t}toCanvas(){if(!Qr.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=Zd(e.width,e.height),n=new Qd(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;enew e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(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 Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(Qr.IS_WEB_ENV){if(Qr.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=tf.get(t)??`image/png`;return id(e,await this.toBlob(n))}else if(Qr.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(Qr.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return Xd(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},rf=nf.read.bind(nf);function af(e,t,n=0,r=null){let i=e/t,a=Dc(i)*t;return r!==null&&a>r&&(a=Math.floor(i)*t),at&&i.push(e)}else{let e=bc(n.data)[1];if(e===c-1||(a=_c(n.data),a[e]e*o[(t+1)%2])),u.boxes.push(n),u.classes.push(t),u.scores.push(a[t])}}l.push(u)}return l}function lf(e,t=null){let n=e.logits,r=n.dims[0];if(t!==null&&t.length!==r)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let i=[];for(let e=0;el[n]&&(l[n]=t[n],u[n]=e)}let d=Array(a.dims[0]);for(let e=0;ee!==void 0);i.push({segmentation:c,labels:f})}return i}function uf(e,t,n,r){let i=[],a=[],o=[];for(let s=0;sn&&(i.push(l),a.push(d),o.push(u))}return[i,a,o]}function df(e,t,n,r=.5,i=.8){let a=[],o=0,s=0,c=t[n].data;for(let t=0;t=r&&++s;let l=o>0&&s>0;return l&&=o/s>i,[l,a]}function ff(e,t,n,r,i,a=null,o=null){let[s,c]=o??e[0].dims,l=new q(`int32`,new Int32Array(s*c),[s,c]),u=[];if(o!==null)for(let t=0;tf[e]&&(d[e]=n,f[e]=i[e])}let p=0,m=l.data;for(let a=0;a200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/n)*n,s=Math.round(t/n)*n;if(a*o*s>i){let r=Math.sqrt(a*e*t/i);o=Math.max(n,Math.floor(e/r/n)*n),s=Math.max(n,Math.floor(t/r/n)*n)}else if(a*o*si?c=Math.floor(i*s/r):i>r&&(s=Math.floor(r*c/i)),await e.resize(c,s,{resample:n}))}async crop_margin(e,t=200){let n=e.clone().grayscale(),r=yc(n.data)[0],i=bc(n.data)[0]-r;if(i===0)return e;let a=t/255,o=n.width,s=n.height,c=0,l=0,u=n.data;for(let e=0;ethis.preprocess(e)));return{pixel_values:wl(n.map(e=>e.pixel_values),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}static async from_pretrained(e,t={}){let n=await mc(e,Yu,!0,t);return new this(n)}},_f={};Ar(_f,{BeitFeatureExtractor:()=>vf,BitImageProcessor:()=>yf,CHMv2ImageProcessor:()=>xf,CLIPFeatureExtractor:()=>Cf,CLIPImageProcessor:()=>Sf,ChineseCLIPFeatureExtractor:()=>bf,ConvNextFeatureExtractor:()=>Tf,ConvNextImageProcessor:()=>wf,DINOv3ViTImageProcessor:()=>Af,DPTFeatureExtractor:()=>Pf,DPTImageProcessor:()=>Nf,DeiTFeatureExtractor:()=>Df,DeiTImageProcessor:()=>Ef,DetrFeatureExtractor:()=>kf,DetrImageProcessor:()=>Of,DonutFeatureExtractor:()=>Mf,DonutImageProcessor:()=>jf,EfficientNetImageProcessor:()=>Ff,GLPNFeatureExtractor:()=>Hf,Gemma3ImageProcessor:()=>If,Gemma4ImageProcessor:()=>zf,Glm46VImageProcessor:()=>Vf,GroundingDinoImageProcessor:()=>Uf,Idefics3ImageProcessor:()=>Wf,ImageFeatureExtractor:()=>gf,ImageProcessor:()=>gf,JinaCLIPImageProcessor:()=>Kf,Lfm2VlImageProcessor:()=>Qf,LlavaOnevisionImageProcessor:()=>$f,Mask2FormerImageProcessor:()=>np,MaskFormerFeatureExtractor:()=>tp,MaskFormerImageProcessor:()=>ep,MobileNetV1FeatureExtractor:()=>ip,MobileNetV1ImageProcessor:()=>rp,MobileNetV2FeatureExtractor:()=>op,MobileNetV2ImageProcessor:()=>ap,MobileNetV3FeatureExtractor:()=>cp,MobileNetV3ImageProcessor:()=>sp,MobileNetV4FeatureExtractor:()=>up,MobileNetV4ImageProcessor:()=>lp,MobileViTFeatureExtractor:()=>fp,MobileViTImageProcessor:()=>dp,NougatImageProcessor:()=>pp,OwlViTFeatureExtractor:()=>hp,OwlViTImageProcessor:()=>mp,Owlv2ImageProcessor:()=>gp,Phi3VImageProcessor:()=>Sp,PixtralImageProcessor:()=>Cp,PvtImageProcessor:()=>wp,Qwen2VLImageProcessor:()=>Bf,RTDetrImageProcessor:()=>Tp,Sam2ImageProcessor:()=>Ep,Sam3ImageProcessor:()=>Ep,SamImageProcessor:()=>Ep,SapiensFeatureExtractor:()=>Op,SapiensImageProcessor:()=>Dp,SegformerFeatureExtractor:()=>Ap,SegformerImageProcessor:()=>kp,SiglipImageProcessor:()=>jp,SmolVLMImageProcessor:()=>Wf,Swin2SRImageProcessor:()=>Mp,VLMImageProcessor:()=>Gf,ViTFeatureExtractor:()=>Pp,ViTImageProcessor:()=>Np,VitMatteImageProcessor:()=>Fp,VitPoseImageProcessor:()=>Ip,YolosFeatureExtractor:()=>Rp,YolosImageProcessor:()=>Lp});var vf=class extends gf{},yf=class extends gf{},bf=class extends gf{},xf=class extends gf{},Sf=class extends gf{},Cf=class extends Sf{},wf=class extends gf{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw Error(`Size dictionary must contain 'shortest_edge' key.`);if(t<384){let n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},Tf=class extends wf{},Ef=class extends gf{},Df=class extends Ef{},Of=class extends gf{async _call(e){let t=await super._call(e),n=Al([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return cf(...e)}post_process_panoptic_segmentation(...e){return mf(...e)}post_process_instance_segmentation(...e){return hf(...e)}},kf=class extends Of{},Af=class extends gf{},jf=class extends gf{pad_image(e,t,n,r={}){let[i,a,o]=t,s=this.image_mean;Array.isArray(this.image_mean)||(s=Array(o).fill(s));let c=this.image_std;Array.isArray(c)||(c=Array(o).fill(s));let l=s.map((e,t)=>-e/c[t]);return super.pad_image(e,t,n,{center:!0,constant_values:l,...r})}},Mf=class extends jf{},Nf=class extends gf{},Pf=class extends Nf{},Ff=class extends gf{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(e=>e*e))}},If=class extends gf{};function Lf(e,t,n,r,i){let a=r*n**2,o=Math.sqrt(a/(e*t)),s=i*n,c=Math.floor(o*e/s)*s,l=Math.floor(o*t/s)*s;if(c===0&&l===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${s}.`);let u=Math.floor(r/i**2)*s;return c===0?(c=s,l=Math.min(Math.floor(t/e)*s,u)):l===0&&(l=s,c=Math.min(Math.floor(e/t)*s,u)),[c,l]}function Rf(e,t,n,r,i,a,o){let s=Math.floor(t/i),c=Math.floor(n/i),l=s*c,u=i*i*r,d=new Float32Array(a*u),f=0;for(let t=0;ta),0));let l=a.dims[0]/o,u=a.dims[1],d=Math.floor(a.dims[2]/c),f=Math.floor(a.dims[3]/c);return{pixel_values:a.view(l,o,u,Math.floor(d/s),s,c,Math.floor(f/s),s,c).permute(0,3,6,4,7,2,1,5,8).view(l*d*f,u*o*c*c),image_grid_thw:new q(`int64`,[l,d,f],[1,3]),original_sizes:r,reshaped_input_sizes:i}}},Vf=class extends Bf{get_resize_output_image_size(e,t){let n=this.patch_size*this.merge_size,r=this.config.temporal_patch_size??2;return pf(e.height,e.width,n,this.min_pixels,this.max_pixels,r)}},Hf=class extends gf{},Uf=class extends gf{async _call(e){let t=await super._call(e),n=t.pixel_values.dims,r=Ml([n[0],n[2],n[3]]);return{...t,pixel_mask:r}}},Wf=class extends gf{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[n,r]=e.dims.slice(-2),i=r/n;return r>=n?(r=Math.ceil(r/t)*t,n=Math.floor(r/i),n=Math.ceil(n/t)*t):(n=Math.ceil(n/t)*t,r=Math.floor(n*i),r=Math.ceil(r/t)*t),{height:n,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:n=!1}={}){let r;if(!Array.isArray(e))r=[[e]];else{if(e.length===0||!e[0])throw Error(`No images provided.`);r=Array.isArray(e[0])?e:[e]}let i=[],a=[],o=[],s=[],c=[];for(let e of r){let n=await Promise.all(e.map(e=>this.preprocess(e)));s.push(...n.map(e=>e.original_size)),c.push(...n.map(e=>e.reshaped_input_size)),n.forEach(e=>e.pixel_values.unsqueeze_(0));let{longest_edge:r}=this.max_image_size,l;if(t??this.do_image_splitting){let e=Array(n.length),t=Array(n.length);l=await Promise.all(n.map(async(n,i)=>{let a=this.get_resize_for_vision_encoder(n.pixel_values,r),o=await ml(n.pixel_values,{size:[a.height,a.width]}),{frames:s,num_splits_h:c,num_splits_w:l}=await this.split_image(o,this.max_image_size);return e[i]=c,t[i]=l,Cl(s,0)})),a.push(e),o.push(t)}else{let e=[r,r];l=await Promise.all(n.map(t=>ml(t.pixel_values,{size:e}))),a.push(Array(n.length).fill(0)),o.push(Array(n.length).fill(0))}i.push(Cl(l,0))}let l=i.length,[u,d,f,p]=i[0].dims,m,h;if(l===1)m=i[0].unsqueeze_(0),h=Al([l,u,f,p],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0)));h=Al([l,e,f,p],!0);let t=h.data,n=e*f*p;for(let r=0;rn||o>r){s=Math.ceil(a/n),c=Math.ceil(o/r);let t=Math.ceil(a/s),l=Math.ceil(o/c);for(let n=0;ne*this.rescale_factor)}pad_image(e,t,n,r){return super.pad_image(e,t,n,{constant_values:this.constant_values,center:!0,...r})}},Kf=class extends gf{constructor(e){let{resize_mode:t,fill_color:n,interpolation:r,size:i,...a}=e,o=t===`squash`?{width:i,height:i}:t===`shortest`?{shortest_edge:i}:{longest_edge:i},s=r===`bicubic`?3:2;super({...a,size:o,resample:s,do_center_crop:!0,crop_size:i,do_normalize:!0})}};function qf(e,t){return Math.round(e/t)*t}function Jf(e,t,n,r,i){let a=1/0,o=[1,1],s=n*r;for(let n of t){let t=Math.abs(e-n[0]/n[1]);t.5*i*i*n[0]*n[1]&&(o=n)}return o}function Yf(e,t){let n=[],r=new Set;for(let i=e;i<=t;++i)for(let a=1;a<=i;++a)for(let o=1;o<=i;++o){let i=a*o;if(i>=e&&i<=t){let e=a<<16|o;r.has(e)||(r.add(e),n.push([a,o]))}}return n.sort((e,t)=>e[0]*e[1]-t[0]*t[1])}function Xf(e,t){let[n,r,i,a]=e.dims,o=Math.floor(i/t),s=Math.floor(a/t),c=t*t*r,l=e.data,u=new Float32Array(n*o*s*c),d=i*a;for(let e=0;ethis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let n=Yf(this.min_tiles,this.max_tiles),[r,i]=Jf(t/e,n,t,e,this.tile_size);return{grid_width:r,grid_height:i,target_width:this.tile_size*r,target_height:this.tile_size*i}}async _call(e,{return_row_col_info:t=null}={}){let n;n=Array.isArray(e)?Array.isArray(e[0])?e:[e]:[[e]];let r=[],i=[],a=[],o=[],s=[],c=[];for(let e of n){let t=await Promise.all(e.map(e=>this.preprocess(e,{do_pad:!1})));for(let{pixel_values:e}of t){let[,t,n]=e.dims,l=e.unsqueeze_(0),u=this.encoder_patch_size*this.downsample_factor,d=u**2,[f,p]=pf(Math.max(u,t),Math.max(u,n),u,this.min_image_tokens*d,this.max_image_tokens*d).map(e=>Math.max(u,e)),m,h=1,g=1,_=this._is_image_too_large(t,n),v=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(_&&v){let{grid_width:e,grid_height:r,target_width:i,target_height:a}=this._get_grid_layout(t,n);h=r,g=e;let o=await ml(l,{size:[a,i]});m=[];for(let t=0;t(e-this.image_mean[t])/this.image_std[t]);return super.pad_image(e,t,{width:s,height:o},{center:!0,constant_values:c,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||xp(t)%1!=0)throw Error(`num_crops must be a square number >= 4`);Array.isArray(e)||(e=[e]);let n=e.length,r=await Promise.all(e.map(e=>this.preprocess(e))),i=r.map(e=>e.original_size),a=r.map(e=>e.reshaped_input_size),o=[];for(let{pixel_values:e}of r){e.unsqueeze_(0);let[n,r]=e.dims.slice(-2),i=await ml(e,{size:[_p,_p],mode:`bicubic`});if(t>0){let a=[],s=xp(t),c=bp(r/s),l=bp(n/s);for(let t=0;te.map(e=>_p*yp(e/_p)));return{pixel_values:s,original_sizes:i,reshaped_input_sizes:a,image_sizes:new q(`int64`,c.flat(),[n,2]),num_img_tokens:c.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},Cp=class extends gf{get_resize_output_image_size(e,t){let{longest_edge:n}=t;if(n===void 0)throw Error(`size must contain 'longest_edge'`);let[r,i]=e.size,a=Math.max(r,i)/n,o=r,s=i;a>1&&(o=Math.floor(r/a),s=Math.floor(i/a));let{patch_size:c,spatial_merge_size:l}=this.config;if(!l)throw Error(`config must contain 'spatial_merge_size'`);let u=c*l,d=Math.floor((o-1)/u)+1,f=Math.floor((s-1)/u)+1;return[d*u,f*u]}},wp=class extends gf{},Tp=class extends gf{post_process_object_detection(...e){return cf(...e)}},Ep=class extends gf{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let i=mi(e);if(i.length===3)r||(i=[1,...i]),e=[e];else if(i.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;re!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new q(`int64`,e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){let i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let s=[a.height,a.width];for(let a=0;ar&&(t[n]=1);u=new q(`bool`,t,u.dims)}o.push(u)}return o}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}},Dp=class extends gf{post_process_semantic_segmentation(...e){return lf(...e)}},Op=class extends Dp{},kp=class extends gf{post_process_semantic_segmentation(...e){return lf(...e)}},Ap=class extends kp{},jp=class extends gf{},Mp=class extends gf{pad_image(e,t,n,r={}){let[i,a,o]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:`symmetric`,center:!1,constant_values:-1,...r})}},Np=class extends gf{},Pp=class extends Np{},Fp=class extends gf{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let n=await Promise.all(e.map(e=>this.preprocess(e))),r=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:wl(n.map((e,t)=>Cl([e.pixel_values,r[t].pixel_values],0)),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}},Ip=class extends gf{post_process_pose_estimation(e,t,{threshold:n=null}={}){let r=e.tolist(),[i,a,o,s]=e.dims,c=[];for(let e=0;e/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e==`string`&&(e=[e]);let t=[];for(let n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(let[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll(`{input}`,n).replaceAll(e,``));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){let r=this.tasks_answer_post_processing_type.get(t)??`pure_text`;e=e.replaceAll(``,``).replaceAll(``,``);let i;switch(r){case`pure_text`:i=e;break;case`description_with_bboxes`:case`bboxes`:case`phrase_grounding`:case`ocr`:let a=r===`ocr`?`quad_boxes`:`bboxes`,o=e.matchAll(this.regexes[a]),s=[],c=[];for(let[e,t,...r]of o)s.push(t?t.trim():s.at(-1)??``),c.push(r.map((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2]));i={labels:s,[a]:c};break;default:throw Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:i}}async _call(e,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=await this.image_processor(e,n),i=t?this.tokenizer(this.construct_prompts(t),n):{};return{...r,...i}}},Vp=class extends Qu{static tokenizer_class=Ku;static image_processor_class=zp;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.image_seq_length=this.config.image_seq_length;let{boi_token:r,image_token:i,eoi_token:a}=this.tokenizer.config;this.boi_token=r,this.image_token=i,this.eoi_token=a,this.full_image_sequence=` + +${r}${i.repeat(this.image_seq_length)}${a} + +`}async _call(e,t=null,n={}){typeof e==`string`&&(e=[e]);let r;return t&&(r=await this.image_processor(t,n),e=e.map(e=>e.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,n),...r}}},Hp=class extends Qu{static image_processor_class=zp;static feature_extractor_class=Kd;static tokenizer_class=Ku;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:r,boa_token:i,audio_token:a,eoa_token:o,image_token_id:s,boi_token:c,image_token:l,eoi_token:u}=this.tokenizer.config;this.audio_token_id=r,this.boa_token=i,this.audio_token=a,this.full_audio_sequence=` + +${i}${a.repeat(this.audio_seq_length)}${o} + +`,this.image_token_id=s,this.boi_token=c,this.image_token=l,this.full_image_sequence=` + +${c}${l.repeat(this.image_seq_length)}${u} + +`}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;n&&(i=await this.feature_extractor(n,r),e=e.map(e=>e.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,r),e=e.map(e=>e.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a,...i}}},Up=class extends Qu{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:r,boa_token:i,eoa_token:a,image_token:o,boi_token:s,eoi_token:c}=this.tokenizer.config;this.audio_token=r,this.boa_token=i,this.eoa_token=a,this.image_token=o,this.boi_token=s,this.eoi_token=c}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([mc(e,Xu,!0,t),Ku.from_pretrained(e,t),pc(e,Zu,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new zf(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new Fd(n.feature_extractor)),new this(n,a,i)}_compute_audio_num_tokens(e,t){let n=Math.round(t*20/1e3),r=Math.round(t*10/1e3),i=Math.floor(n/2),a=Math.floor((e+i-n-1)/r)+1;if(a<=0)return 0;for(let e=0;e<2;++e)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;if(t){i=await this.image_processor(t,r);let n=i.num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>` + +${this.boi_token}${this.image_token.repeat(n[a++])}${this.eoi_token} + +`))}let a;if(n){let t=Array.isArray(n)?n:[n];a=await this.feature_extractor(t[0],r);let i=this.feature_extractor.config.sampling_rate??16e3,o=0;e=e.map(e=>e.replaceAll(this.audio_token,()=>` + +${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(t[o++].length,i))}${this.eoa_token} + +`))}return{...this.tokenizer(e,r),...i,...a}}},Wp=class extends Qu{static image_processor_class=zp;static tokenizer_class=Ku;static image_token=`<|image_pad|>`;async _call(e,t=null,...n){Array.isArray(e)||(e=[e]);let r,i;if(t&&(r=await this.image_processor(t),i=r.image_grid_thw),i){let t=this.image_processor.config.merge_size**2,n=0,r=this.constructor.image_token,a=i.tolist();e=e.map(e=>{for(;e.includes(r);){let i=Number(a[n++].reduce((e,t)=>e*t,1n));e=e.replace(r,`<|placeholder|>`.repeat(Math.floor(i/t)))}return e.replaceAll(`<|placeholder|>`,r)})}return{...this.tokenizer(e),...r}}},Gp=class extends Wp{static image_token=`<|image|>`},Kp=class extends Qu{static tokenizer_class=Ku;static feature_extractor_class=Kd;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:n,projector_downsample_rate:r}=this.feature_extractor.config,i=Math.floor(n/r),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/n)*i}async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let{input_features:n}=await this.feature_extractor(t);r.input_features=n;let i=this._get_num_audio_features(t.length);r.input_features_mask=new q(`bool`,new Uint8Array(i).fill(1),[1,i]);let a=this.config.audio_token??`<|audio|>`;if(!e.includes(a))throw Error(`The input text does not contain the audio token ${a}.`);e=e.replaceAll(a,a.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}};function qp(e,t){let n=e.dims.at(-1)-1,r=e.tolist();r.fill(!1,0,1),r.fill(!1,n);let i=t.tolist();return r.map((e,t)=>e?t:null).filter(e=>e!==null).map(e=>i[e])}var Jp=class extends Qu{static tokenizer_class=Ku;static image_processor_class=zp;async _call(e,t,n={}){let r=e?await this.image_processor(e,n):{};return{...t?this.tokenizer(t,n):{},...r}}post_process_grounded_object_detection(e,t,{box_threshold:n=.25,text_threshold:r=.25,target_sizes:i=null}={}){let{logits:a,pred_boxes:o}=e,s=a.dims[0];if(i!==null&&i.length!==s)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let c=a.dims.at(1),l=a.sigmoid(),u=l.max(-1).tolist(),d=o.tolist().map(e=>e.map(e=>sf(e))),f=[];for(let e=0;ee.map((e,t)=>e*a[(t+1)%2])));let o=u[e],s=[],p=[],m=[];for(let i=0;i`+i.repeat(e);o+=` +`}return o+=` +${r}${a}`+i.repeat(e)+`${r}`,o}function Xp(e,t,n,r){return`${t}${r}`+n.repeat(e)+`${t}`}function Zp(e,t,n,r,i,a){return e===0&&t===0?Xp(n,r,i,a):Yp(n,e,t,r,i,a)}var Qp=class extends Qu{static image_processor_class=zp;static tokenizer_class=Ku;static uses_processor_config=!0;fake_image_token=``;image_token=``;global_img_token=``;async _call(e,t=null,n={}){n.return_row_col_info??=!0;let r;t&&(r=await this.image_processor(t,n)),Array.isArray(e)||(e=[e]);let i=r.rows??[Array(e.length).fill(0)],a=r.cols??[Array(e.length).fill(0)],o=this.config.image_seq_len,s=[],c=[];for(let t=0;tZp(e,l[t],o,this.fake_image_token,this.image_token,this.global_img_token)),d=n.split(this.image_token);if(d.length===0)throw Error(`The image token should be present in the text.`);let f=d[0];for(let e=0;ee.images).flatMap(e=>e.images).map(e=>nf.read(e)));let r=this.tokenizer,i=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:n}),a=e=>r.encode(e,{add_special_tokens:!1}),o=i.split(this.image_tag),s=o.length-1;if(t.length!==s)throw Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${s})`);let[c,l,u]=r.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),d=a(o[0]),f=Array(d.length).fill(!1);for(let e=1;e0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...m,...e}}return m}},em=class extends Qu{static tokenizer_class=Ku;static image_processor_class=zp;async _call(e=null,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=e?this.tokenizer(e,n):{},i=t?await this.image_processor(t,n):{};return{...r,...i}}},tm=class extends Qu{static tokenizer_class=Ku;static image_processor_class=zp;async _call(e,t=null,n={}){let{image_rows:r,image_cols:i,image_sizes:a,...o}=await this.image_processor(e,{...n,return_row_col_info:!0});if(t){let e=this.config.image_token??``,{tile_size:n=512,downsample_factor:o=2,encoder_patch_size:s=16,use_thumbnail:c=!0}=this.image_processor.config,l=e=>Math.ceil(Math.floor(e/s)/o),u=l(n)**2,d=this.config.image_start_token??`<|image_start|>`,f=this.config.image_end_token??`<|image_end|>`,p=this.config.image_thumbnail??`<|img_thumbnail|>`;Array.isArray(t)||(t=[t]);let m=0;t=t.map(t=>{let n=t.split(e);return n[0]+n.slice(1).map(t=>{let n=m++,[o,s]=a[n],h=r[n],g=i[n],_=l(o)*l(s),v=d;if(h>1||g>1){let t=e.repeat(u);for(let e=0;e`+t;c&&(v+=p+e.repeat(_))}else v+=e.repeat(_);return v+f+t}).join(``)})}return{...o,...t?this.tokenizer(t,n):{}}}},nm=class extends Qu{static tokenizer_class=Ku;static image_processor_class=zp;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,patch_size:a,num_additional_image_tokens:o}=this.config,s=Math.floor(e/a)*Math.floor(n/a)+o;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e0?i.reduce((e,t)=>e*t,1):0;c.push(n),s.push(a)}return[i(c),s]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}batch_decode([e,t,n]){let[r,i]=this._decode_helper(e,`char`),[a,o]=this._decode_helper(t,`bpe`),[s,c]=this._decode_helper(n,`wp`),l=[],u=[];for(let e=0;e`;function cm(e,t,n,r,i){return`${r.repeat(n*i)}${t}${e} +`}var lm=class extends Qu{static tokenizer_class=Ku;static image_processor_class=zp;static uses_processor_config=!1;async _call(e,t=null,n={}){t||=(V.warn(`You are using PaliGemma without a text prefix. It will perform as a picture-captioning model.`),``),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=this.tokenizer.bos_token,i=this.image_processor.config.image_seq_length,a;t.some(e=>e.includes(sm))?a=t.map(e=>{let t=e.replaceAll(sm,sm.repeat(i)),n=t.lastIndexOf(sm),a=n===-1?0:n+sm.length;return t.slice(0,a)+r+t.slice(a)+` +`}):(V.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(t=>cm(t,r,i,sm,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},um=`<|image|>`,dm=/<\|image_\d+\|>/g,fm=class extends Qu{static image_processor_class=zp;static tokenizer_class=Ku;async _call(e,t=null,{padding:n=!0,truncation:r=!0,num_crops:i=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:i});let{num_img_tokens:s}=o,c=e.map((e,t)=>e.split(dm).join(um.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(um);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},pm=class extends Qu{static tokenizer_class=Ku;static image_processor_class=zp;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:a,image_end_token:o,patch_size:s,spatial_merge_size:c}=this.config,l=s*c,u=Math.floor(e/l),d=Math.floor(n/l);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;eTm(e,o)),c=s.map(e=>e.length),l=s.flat(),u=(await Promise.all(l.map(e=>this.feature_extractor(e,n)))).map(e=>e.input_features);r.audio_values=u.length>1?Cl(u,0):u[0];let d=i[0];for(let e=0;e0){if(l>zs)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${zs}).`);let t=Wm(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(new Promise(async(i,a)=>{let o=await fc(e,t,!0,r,s);i(o instanceof Uint8Array?{path:n,data:o}:n)}))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await fc(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function qm(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=rl(n.device??a.device,t,{warn:e=>V.info(e)}),s=Uc(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=ll(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>V.info(e)});if(!cl.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(al).join(`, `)}`);if(o===`webgpu`&&!Qr.IS_NODE_ENV&&l===al.fp16&&!await il())throw Error(`The device (${o}) does not support fp16.`);let u=a.kv_cache_dtype,d=u?typeof u==`string`?u:u[l]??`float32`:void 0;if(d&&![`float32`,`float16`].includes(d))throw Error(`Invalid kv_cache_dtype: ${d}. Should be one of: float32, float16`);let f=cl[l],p={...n.session_options};p.executionProviders??=s;let m=a.free_dimension_overrides;m?p.freeDimensionOverrides??=m:o.startsWith(`webnn`)&&!p.freeDimensionOverrides&&V.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let h=Gm(e,t,n,f),g=await Km(e,t,f,n,n.use_external_data_format??a.use_external_data_format,p);if(g.length>0&&(!Qr.IS_NODE_ENV||g.some(e=>typeof e!=`string`))&&(p.externalData=g),r&&o===`webgpu`&&u!==!1){let e=zm(n.config,{prefix:`present`,session_name:i});if(Object.keys(e).length>0&&!Qc()){let t={};for(let n in e)t[n]=`gpu-buffer`;p.preferredOutputLocation=t}}return{buffer_or_path:await h,session_options:p,session_config:{dtype:l,kv_cache_dtype:d,device:o}}}async function Jm(e,t,n,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async i=>{let a=r?.[i]??!1,{buffer_or_path:o,session_options:s,session_config:c}=await qm(e,t[i],n,a,i);return[i,await qc(o,s,c)]})))}function Ym(e){for(let t in e)Xc(e[t])?e[t]=new q(e[t]):typeof e[t]==`object`&&Ym(e[t]);return e}async function Xm(e,t){let n=Zm(e,t);try{return Ym(await Yc(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return Qr.IS_NODE_ENV&&typeof Float16Array<`u`&&n.cpuData instanceof Float16Array&&(n.cpuData=new Uint16Array(n.cpuData.buffer)),[e,n]}))))}catch(e){let t=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n={type:t.type,dims:t.dims,location:t.location};return n.location!==`gpu-buffer`&&(n.data=t.data),[e,n]}));throw V.error(`An error occurred during model execution: "${e}".`),V.error(`Inputs given to model:`,t),e}}function Zm(e,t){let n=Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];if(!(e instanceof q)){r.push(i);continue}n[i]=Qc()?e.clone():e}if(r.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(`, `)}.`);let i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let n=Object.keys(t).filter(t=>!e.inputNames.includes(t));V.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${n.join(`, `)}".`)}return n}var Qm=class{},$m=class extends Qm{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},eh=class extends Qm{constructor({logits:e}){super(),this.logits=e}},th=class extends Qm{constructor({logits:e}){super(),this.logits=e}},nh=class extends Qm{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},rh=class extends Qm{constructor({logits:e}){super(),this.logits=e}},ih=class extends Qm{constructor({alphas:e}){super(),this.alphas=e}},ah=class extends li{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},oh=class extends li{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},sh=class extends li{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(let t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}},ch=class extends ah{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){let e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}let s=vc(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>bc(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},ph=class extends ah{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r1 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 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.`);let n=e.length,r=t.slice([0,n],null),i=t.slice([n,t.dims[0]],null);for(let e=0;ee.length>=this.max_length)}},wh=class extends xh{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},Th=class extends li{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 n=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){return Fs(e)}static getSampler(e){if(e.do_sample)return new Dh(e);if(e.num_beams>1)return new Oh(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 Eh(e)}},Eh=class extends Th{async sample(e){let t=bc(e.data)[1];return[[BigInt(t),0]]}},Dh=class extends Th{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await gl(e,t),i=_c(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},Oh=class extends Th{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await gl(e,t),i=_c(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},kh=class{constructor(e){if(e)for(let t in e){if(t in this)throw TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let n=e[t];if(!(n instanceof q))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith(`past_key_values.`))return e[t].dims.at(-2);throw Error(`Unable to determine sequence length from the cache.`)}update(e){for(let t in e){let n=this[t],r=e[t];n&&n!==r&&n.location===`gpu-buffer`&&n.dispose(),this[t]=r}}async dispose(){let e=[];for(let t of Object.values(this))t.location===`gpu-buffer`&&e.push(t.dispose());await Promise.all(e)}},Y={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},Ah={[Y.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??`model`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??`model`})},[Y.Seq2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.Vision2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.Musicgen]:{sessions:()=>({model:`text_encoder`,decoder_model_merged:`decoder_model_merged`,encodec_decode:`encodec_decode`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.EncoderDecoder]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0}},[Y.MaskGeneration]:{sessions:()=>({model:`vision_encoder`,prompt_encoder_mask_decoder:`prompt_encoder_mask_decoder`})},[Y.ImageTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ah[Y.ImageTextToText].text_only_sessions};return n||(r.vision_encoder=`vision_encoder`),e.is_encoder_decoder&&(r.model=`encoder_model`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.AudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ah[Y.AudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ah[Y.ImageAudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`,r.vision_encoder=`vision_encoder`),r},optional_configs:{generation_config:`generation_config.json`}},[Y.Phi3V]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`model`,vision_encoder:`vision_encoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.MultiModality]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`language_model`,lm_head:`lm_head`,gen_head:`gen_head`,gen_img_embeds:`gen_img_embeds`,image_decode:`image_decode`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.AutoEncoder]:{sessions:()=>({encoder_model:`encoder_model`,decoder_model:`decoder_model`})},[Y.Supertonic]:{sessions:()=>({text_encoder:`text_encoder`,latent_denoiser:`latent_denoiser`,voice_decoder:`voice_decoder`})},[Y.Chatterbox]:{sessions:()=>({embed_tokens:`embed_tokens`,speech_encoder:`speech_encoder`,model:`language_model`,conditional_decoder:`conditional_decoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Y.VoxtralRealtime]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ah[Y.VoxtralRealtime].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:`generation_config.json`}},default:{sessions:(e,t)=>({model:t.model_file_name??`model`})}};function jh(e,t,n={}){let r=Ah[e]??Ah.default;return{sessions:r.sessions(t,n,n.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function Mh(e,{warn:t=!0}={}){let n=e.architectures||[];for(let e of n){let t=Vh.get(e);if(t!==void 0)return t}if(e.model_type){let t=Vh.get(e.model_type);if(t!==void 0)return t;for(let t of Object.values(Fh))if(t.has(e.model_type)){let n=Vh.get(t.get(e.model_type));if(n!==void 0)return n}}if(t){let t=n.length>0?n.join(`, `):`(none)`;V.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${t}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${qu}`)}return Y.EncoderOnly}function Nh(e,{config:t=null,cache_dir:n=null,local_files_only:r=!1,revision:i=`main`}={}){return t===null?tc(JSON.stringify([e,n,r,i]),()=>Hm.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})):Hm.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})}async function Ph(e,{config:t=null,dtype:n=null,device:r=null,model_file_name:i=null}={}){t=await Nh(e,{config:t});let a=[`config.json`],o=t[`transformers.js_config`]??{},s=o.use_external_data_format,c=`onnx`,l=r??o.device,u=n??o.dtype,d=Mh(t),f=(e,t=null)=>{t??=e;let n=cl[ll(u,e,rl(l,e))]??``,r=`${t}${n}.onnx`,i=`${c}/${r}`;a.push(i);let o=Um(s,r,e);for(let e of Wm(r,o)){let t=`${c}/${e}`;a.push(t)}},{sessions:p,optional_configs:m}=jh(d,t,{model_file_name:i});for(let[e,t]of Object.entries(p))f(e,t);if(m)for(let e of Object.values(m))a.push(e);return a}var Fh=null;function Ih(e){Fh=e}function Lh(e){if(e instanceof q)return e;if(e.length===0)throw Error(`items must be non-empty`);if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[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 q(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}else return new q(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function Rh(e){return new q(`bool`,[e],[1])}var zh={[Y.DecoderOnly]:{can_generate:!0,forward:Xh,prepare_inputs:ng},[Y.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Xh,prepare_inputs:ng},[Y.Seq2Seq]:{can_generate:!0,forward:Wh,prepare_inputs:rg},[Y.Vision2Seq]:{can_generate:!0,forward:Wh,prepare_inputs:rg},[Y.Musicgen]:{can_generate:!0,forward:Wh},[Y.EncoderDecoder]:{can_generate:!1,forward:Wh},[Y.ImageTextToText]:{can_generate:!0,forward:$h,prepare_inputs:ig},[Y.AudioTextToText]:{can_generate:!0,forward:Qh,prepare_inputs:ig},[Y.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:ig},[Y.Phi3V]:{can_generate:!0,prepare_inputs:ig},[Y.MultiModality]:{can_generate:!0},[Y.AutoEncoder]:{can_generate:!1,forward:Kh},[Y.Chatterbox]:{can_generate:!0,forward:Gh},[Y.VoxtralRealtime]:{can_generate:!0,prepare_inputs:ng},default:{can_generate:!1,forward:Gh}};function Bh(e,t){let n=Vh.get(e),r=!1,i=t?.architectures?.[0];if(i&&i!==e&&e?.endsWith(`ForCausalLM`)&&i.endsWith(`ForConditionalGeneration`)){let e=Vh.get(i);e!==void 0&&(n=e,r=!0)}let a=zh[n]??zh.default,o=Ah[n]??Ah.default;return{typeConfig:{...a,...o},textOnly:r,modelType:n}}var Vh=new Map,Hh=new Map,Uh=new Map,X=class extends li{main_input_name=`input_ids`;forward_params=[`input_ids`,`attention_mask`];_return_dict_in_generate_keys=null;constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;let{typeConfig:r}=Bh(Uh.get(this.constructor),e);this.can_generate=r.can_generate,this._forward=r.forward,this._prepare_inputs_for_generation=r.prepare_inputs,this.can_generate&&this.forward_params.push(`past_key_values`),this.custom_config=this.config[`transformers.js_config`]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d},p=Uh.get(this);n=f.config=await Hm.from_pretrained(e,f);let{typeConfig:m,textOnly:h,modelType:g}=Bh(p,n);if(g===void 0){let e=p??n?.model_type;e!==`custom`&&V.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${qu}.`)}if(t&&!(t instanceof di)){let r={};try{let t=await Ph(e,{config:n,dtype:l,device:c,model_file_name:o});(await Promise.all(t.map(t=>rc(e,t,f)))).forEach((e,n)=>{if(e.exists){let i=t[n]===`config.json`;r[t[n]]={loaded:i?e.size??0:0,total:e.size??0}}})}catch(e){V.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(r).length>0&&(f.progress_callback=new di(t,r))}let _=[Jm(e,m.sessions(n,f,h),f,m.cache_sessions)];m.optional_configs&&_.push(cg(e,m.optional_configs,f));let v=await Promise.all(_);return new this(n,...v)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,n=null){let r=new sh;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new mh(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new ph(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new _h(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new hh(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new gh(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new ch(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new lh(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new uh(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new dh(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new vh(e.guidance_scale)),e.temperature===0&&e.do_sample&&(V.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new yh(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=bh){let r={...this.config};for(let e of[`decoder`,`generator`,`text_config`])e in r&&Object.assign(r,r[e]);let i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,vi(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new Sh;return e.max_length!==null&&n.push(new Ch(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new wh(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[Fh.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Fh.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Fh.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Fh.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Uh.get(this.constructor),n=new Set,r=this.config.model_type;for(let t of e){let e=t?.get(r);e&&n.add(e)}let i=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(`, `)}`),Error(i)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error(`prepare_inputs_for_generation is not implemented for this model.`);return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=qh(t,n.past_key_values),n.input_ids=new q(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n&&(n.decoder_attention_mask=Cl([n.decoder_attention_mask,Ml([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=Cl([n.attention_mask,Ml([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){let r=vi(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes(`inputs_embeds`)&&!t.inputs_embeds&&`_prepare_inputs_embeds`in this){let{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...vi(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await Gh(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=Cl([i,jl(i,0)],0),`attention_mask`in t&&(t.attention_mask=Cl([t.attention_mask,Fl(t.attention_mask)],0));else if(t.decoder_input_ids){let e=Lh(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(i.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=Cl(Array.from({length:e},()=>i),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:o,...s}=n;if(!(o instanceof q)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=i,this.config.model_type===`musicgen`)o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=Lh(o)}return s.decoder_attention_mask=Nl(o),{input_ids:o,model_inputs:s}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:s,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),l=this.config.is_encoder_decoder;l&&(`encoder_outputs`in s||(s=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:s,model_input_name:c,generation_config:t})));let u;l?{input_ids:u,model_inputs:s}=this._prepare_decoder_input_ids_for_generation({batch_size:s[c].dims.at(0),model_input_name:c,model_kwargs:s,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):u=s[c];let d=u.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=d+t.max_new_tokens);let f=this._get_logits_processor(t,d,n),p=this._get_stopping_criteria(t,r),m=s[c].dims.at(0),h=Th.getSampler(t),g=Array(m).fill(0),_=u.tolist();i&&i.put(_);let v,y={},b={};for(;;){if(s=this.prepare_inputs_for_generation(_,s,t),v=await this.forward(s),t.return_dict_in_generate)if(t.output_attentions){let e=Jh(v);for(let t in e)t in y||(y[t]=[]),y[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(b,vi(v,this._return_dict_in_generate_keys));let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;te))break;s=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:v,model_inputs:s,is_encoder_decoder:l})}i&&i.end();let x=new q(`int64`,_.flat(),[_.length,_[0].length]),S=qh(v,s.past_key_values),C=new Set(Object.values(S));for(let e of Object.values(v))e.location===`gpu-buffer`&&!C.has(e)&&e.dispose();return`past_key_values`in a||t.return_dict_in_generate||await S.dispose(),t.return_dict_in_generate?{sequences:x,past_key_values:S,...y,...b}:x}async _encode_input(e,t,n){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let r=this.sessions[e];return(await Xm(r,vi(t,r.inputNames)))[n]}async encode_image(e){return this._encode_input(`vision_encoder`,e,`image_features`)}async encode_text(e){return this._encode_input(`embed_tokens`,e,`inputs_embeds`)}async encode_audio(e){return this._encode_input(`audio_encoder`,e,`audio_features`)}};async function Wh(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,decoder_attention_mask:a,...o}=t;return n||=(await Gh(e,vi(t,e.sessions.model.inputNames))).last_hidden_state,o.input_ids=i,o.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes(`encoder_attention_mask`)&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await Xh(e,o,!0)}async function Gh(e,t){let n=e.sessions.model,r=vi(t,n.inputNames);if(n.inputNames.includes(`inputs_embeds`)&&!r.inputs_embeds){if(!t.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(n.inputNames.includes(`token_type_ids`)&&!r.token_type_ids){if(!r.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");r.token_type_ids=Fl(r.input_ids)}if(n.inputNames.includes(`pixel_mask`)&&!r.pixel_mask){if(!r.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let e=r.pixel_values.dims;r.pixel_mask=Ml([e[0],e[2],e[3]])}return await Xm(n,r)}async function Kh(e,t){let n=await e.encode(t);return await e.decode(n)}function qh(e,t){let n=Object.create(null);for(let r in e)if(r.startsWith(`present`)){let i=r.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present`,`past_key_values`);r.includes(`encoder`)&&t?n[i]=t[i]:n[i]=e[r]}return t?(t.update(n),t):new kh(n)}function Jh(e){let t={};for(let n of[`cross_attentions`,`encoder_attentions`,`decoder_attentions`])for(let r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}function Yh(e,t,n){if(n&&Object.keys(n).length>0)return Object.assign(t,n),n;let r=e.sessions.decoder_model_merged??e.sessions.model,i=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=r?.config?.kv_cache_dtype??`float32`,o=a===`float16`?ul.float16:ul.float32,s=zm(e.config,{batch_size:i}),c=Object.create(null);for(let e in s){let n=new q(a,new o(s[e].reduce((e,t)=>e*t,1)),s[e]);t[e]=n,c[e]=n}return n?(n.update(c),n):new kh(c)}async function Xh(e,t,n=!1){let r=e.sessions[n?`decoder_model_merged`:`model`],{past_key_values:i,...a}=t;return r.inputNames.includes(`use_cache_branch`)&&(a.use_cache_branch=Rh(i!=null&&Object.keys(i).length>0)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=tg(a,i,+!![`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type))),r.inputNames.includes(`num_logits_to_keep`)&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new q(`int64`,[0n],[])),Yh(e,a,i),await Xm(r,vi(a,r.inputNames))}async function Zh(e,{encode_function:t,merge_function:n,modality_input_names:r,modality_output_name:i,input_ids:a=null,attention_mask:o=null,position_ids:s=null,inputs_embeds:c=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,...f}){if(!c){c=await e.encode_text({input_ids:a,...f});let s=vi(f,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...f});({inputs_embeds:c,attention_mask:o}=n({[i]:e,inputs_embeds:c,input_ids:a,attention_mask:o}))}else if(l&&a.dims[1]===1){let e=a.dims[1],t=l.get_seq_length();o=Cl([Ml([a.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}}}if(!s&&[`qwen2_vl`,`qwen2_vl_text`,`qwen2_5_vl`,`qwen2_5_vl_text`,`qwen3_vl`,`qwen3_vl_text`,`qwen3_vl_moe`,`qwen3_vl_moe_text`,`qwen3_5`,`qwen3_5_text`,`qwen3_5_moe`,`qwen3_5_moe_text`,`glm_ocr`,`glm_ocr_text`].includes(e.config.model_type)){let{image_grid_thw:t,video_grid_thw:n}=f;[s]=e.get_rope_index(a,t,n,o)}return await Xh(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d},!0)}async function Qh(e,t){return await Zh(e,{...t,modality_input_names:[`audio_values`,`input_features`],modality_output_name:`audio_features`,encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function $h(e,t){return await Zh(e,{...t,modality_input_names:[`pixel_values`],modality_output_name:`image_features`,encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function eg(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;ee.dims[1]||i[e.at(-1)])),{...n,decoder_input_ids:Lh(t)}}function ig(e,...t){return e.config.is_encoder_decoder?rg(e,...t):ng(e,...t)}function ag({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i}){let a=r.tolist().map(t=>t.reduce((t,n,r)=>(n==e&&t.push(r),t),[])),o=a.reduce((e,t)=>e+t.length,0),s=n.dims[0];if(o!==s)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${s}`);let c=0;for(let e=0;e[r,await mc(e,t[r],!1,n)])))}var lg={};Ar(lg,{ASTForAudioClassification:()=>Eg,ASTModel:()=>Tg,ASTPreTrainedModel:()=>wg,AfmoeForCausalLM:()=>bg,AfmoeModel:()=>yg,AfmoePreTrainedModel:()=>vg,AlbertForMaskedLM:()=>mg,AlbertForQuestionAnswering:()=>pg,AlbertForSequenceClassification:()=>fg,AlbertModel:()=>dg,AlbertPreTrainedModel:()=>ug,ApertusForCausalLM:()=>_g,ApertusModel:()=>gg,ApertusPreTrainedModel:()=>hg,ArceeForCausalLM:()=>Cg,ArceeModel:()=>Sg,ArceePreTrainedModel:()=>xg,BartForConditionalGeneration:()=>kg,BartForSequenceClassification:()=>Ag,BartModel:()=>Og,BartPretrainedModel:()=>Dg,BeitForImageClassification:()=>Ng,BeitModel:()=>Mg,BeitPreTrainedModel:()=>jg,BertForMaskedLM:()=>Ig,BertForQuestionAnswering:()=>zg,BertForSequenceClassification:()=>Lg,BertForTokenClassification:()=>Rg,BertModel:()=>Fg,BertPreTrainedModel:()=>Pg,BlenderbotForConditionalGeneration:()=>Hg,BlenderbotModel:()=>Vg,BlenderbotPreTrainedModel:()=>Bg,BlenderbotSmallForConditionalGeneration:()=>Gg,BlenderbotSmallModel:()=>Wg,BlenderbotSmallPreTrainedModel:()=>Ug,BloomForCausalLM:()=>Jg,BloomModel:()=>qg,BloomPreTrainedModel:()=>Kg,CHMv2ForDepthEstimation:()=>c_,CHMv2PreTrainedModel:()=>s_,CLIPModel:()=>m_,CLIPPreTrainedModel:()=>p_,CLIPSegForImageSegmentation:()=>x_,CLIPSegModel:()=>b_,CLIPSegPreTrainedModel:()=>y_,CLIPTextModel:()=>h_,CLIPTextModelWithProjection:()=>g_,CLIPVisionModel:()=>__,CLIPVisionModelWithProjection:()=>v_,CamembertForMaskedLM:()=>Zg,CamembertForQuestionAnswering:()=>e_,CamembertForSequenceClassification:()=>Qg,CamembertForTokenClassification:()=>$g,CamembertModel:()=>Xg,CamembertPreTrainedModel:()=>Yg,ChatterboxModel:()=>i_,ChatterboxPreTrainedModel:()=>r_,ChineseCLIPModel:()=>o_,ChineseCLIPPreTrainedModel:()=>a_,ClapAudioModelWithProjection:()=>f_,ClapModel:()=>u_,ClapPreTrainedModel:()=>l_,ClapTextModelWithProjection:()=>d_,CodeGenForCausalLM:()=>w_,CodeGenModel:()=>C_,CodeGenPreTrainedModel:()=>S_,Cohere2ForCausalLM:()=>A_,Cohere2Model:()=>k_,Cohere2PreTrainedModel:()=>O_,CohereAsrForConditionalGeneration:()=>N_,CohereAsrModel:()=>M_,CohereAsrPreTrainedModel:()=>j_,CohereForCausalLM:()=>D_,CohereModel:()=>E_,CoherePreTrainedModel:()=>T_,ConvBertForMaskedLM:()=>I_,ConvBertForQuestionAnswering:()=>z_,ConvBertForSequenceClassification:()=>L_,ConvBertForTokenClassification:()=>R_,ConvBertModel:()=>F_,ConvBertPreTrainedModel:()=>P_,ConvNextForImageClassification:()=>H_,ConvNextModel:()=>V_,ConvNextPreTrainedModel:()=>B_,ConvNextV2ForImageClassification:()=>G_,ConvNextV2Model:()=>W_,ConvNextV2PreTrainedModel:()=>U_,DFineForObjectDetection:()=>Q_,DFineModel:()=>Z_,DFinePreTrainedModel:()=>X_,DINOv3ConvNextModel:()=>Hv,DINOv3ConvNextPreTrainedModel:()=>Vv,DINOv3ViTModel:()=>Wv,DINOv3ViTPreTrainedModel:()=>Uv,DPTForDepthEstimation:()=>ty,DPTModel:()=>ey,DPTPreTrainedModel:()=>$v,DacDecoderModel:()=>iv,DacDecoderOutput:()=>ev,DacEncoderModel:()=>rv,DacEncoderOutput:()=>$_,DacModel:()=>nv,DacPreTrainedModel:()=>tv,DebertaForMaskedLM:()=>sv,DebertaForQuestionAnswering:()=>uv,DebertaForSequenceClassification:()=>cv,DebertaForTokenClassification:()=>lv,DebertaModel:()=>ov,DebertaPreTrainedModel:()=>av,DebertaV2ForMaskedLM:()=>gv,DebertaV2ForQuestionAnswering:()=>yv,DebertaV2ForSequenceClassification:()=>_v,DebertaV2ForTokenClassification:()=>vv,DebertaV2Model:()=>hv,DebertaV2PreTrainedModel:()=>mv,DecisionTransformerModel:()=>xv,DecisionTransformerPreTrainedModel:()=>bv,DeepseekV3ForCausalLM:()=>pv,DeepseekV3Model:()=>fv,DeepseekV3PreTrainedModel:()=>dv,DeiTForImageClassification:()=>wv,DeiTModel:()=>Cv,DeiTPreTrainedModel:()=>Sv,DepthAnythingForDepthEstimation:()=>Ev,DepthAnythingPreTrainedModel:()=>Tv,DepthProForDepthEstimation:()=>Ov,DepthProPreTrainedModel:()=>Dv,DetrForObjectDetection:()=>jv,DetrForSegmentation:()=>Mv,DetrModel:()=>Av,DetrObjectDetectionOutput:()=>Nv,DetrPreTrainedModel:()=>kv,DetrSegmentationOutput:()=>Pv,Dinov2ForImageClassification:()=>Lv,Dinov2Model:()=>Iv,Dinov2PreTrainedModel:()=>Fv,Dinov2WithRegistersForImageClassification:()=>Bv,Dinov2WithRegistersModel:()=>zv,Dinov2WithRegistersPreTrainedModel:()=>Rv,DistilBertForMaskedLM:()=>Xv,DistilBertForQuestionAnswering:()=>Yv,DistilBertForSequenceClassification:()=>qv,DistilBertForTokenClassification:()=>Jv,DistilBertModel:()=>Kv,DistilBertPreTrainedModel:()=>Gv,DonutSwinModel:()=>Qv,DonutSwinPreTrainedModel:()=>Zv,EdgeTamModel:()=>kT,EfficientNetForImageClassification:()=>iy,EfficientNetModel:()=>ry,EfficientNetPreTrainedModel:()=>ny,ElectraForMaskedLM:()=>sy,ElectraForQuestionAnswering:()=>uy,ElectraForSequenceClassification:()=>cy,ElectraForTokenClassification:()=>ly,ElectraModel:()=>oy,ElectraPreTrainedModel:()=>ay,Ernie4_5ForCausalLM:()=>py,Ernie4_5Model:()=>fy,Ernie4_5PretrainedModel:()=>dy,EsmForMaskedLM:()=>gy,EsmForSequenceClassification:()=>_y,EsmForTokenClassification:()=>vy,EsmModel:()=>hy,EsmPreTrainedModel:()=>my,EuroBertForMaskedLM:()=>xy,EuroBertForSequenceClassification:()=>Sy,EuroBertForTokenClassification:()=>Cy,EuroBertModel:()=>by,EuroBertPreTrainedModel:()=>yy,ExaoneForCausalLM:()=>Ey,ExaoneModel:()=>Ty,ExaonePreTrainedModel:()=>wy,FalconForCausalLM:()=>ky,FalconH1ForCausalLM:()=>My,FalconH1Model:()=>jy,FalconH1PreTrainedModel:()=>Ay,FalconModel:()=>Oy,FalconPreTrainedModel:()=>Dy,FastViTForImageClassification:()=>Fy,FastViTModel:()=>Py,FastViTPreTrainedModel:()=>Ny,Florence2ForConditionalGeneration:()=>Ly,Florence2PreTrainedModel:()=>Iy,GLPNForDepthEstimation:()=>_b,GLPNModel:()=>gb,GLPNPreTrainedModel:()=>hb,GPT2LMHeadModel:()=>Mb,GPT2Model:()=>jb,GPT2PreTrainedModel:()=>Ab,GPTBigCodeForCausalLM:()=>bb,GPTBigCodeModel:()=>yb,GPTBigCodePreTrainedModel:()=>vb,GPTJForCausalLM:()=>Fb,GPTJModel:()=>Pb,GPTJPreTrainedModel:()=>Nb,GPTNeoForCausalLM:()=>Cb,GPTNeoModel:()=>Sb,GPTNeoPreTrainedModel:()=>xb,GPTNeoXForCausalLM:()=>Eb,GPTNeoXModel:()=>Tb,GPTNeoXPreTrainedModel:()=>wb,Gemma2ForCausalLM:()=>Uy,Gemma2Model:()=>Hy,Gemma2PreTrainedModel:()=>Vy,Gemma3ForCausalLM:()=>Zy,Gemma3ForConditionalGeneration:()=>Xy,Gemma3Model:()=>Yy,Gemma3PreTrainedModel:()=>Jy,Gemma3nForCausalLM:()=>eb,Gemma3nForConditionalGeneration:()=>$y,Gemma3nPreTrainedModel:()=>Qy,Gemma4ForCausalLM:()=>nb,Gemma4ForConditionalGeneration:()=>tb,GemmaForCausalLM:()=>By,GemmaModel:()=>zy,GemmaPreTrainedModel:()=>Ry,GlmForCausalLM:()=>ab,GlmModel:()=>ib,GlmMoeDsaForCausalLM:()=>cb,GlmMoeDsaModel:()=>sb,GlmMoeDsaPreTrainedModel:()=>ob,GlmOcrForConditionalGeneration:()=>mb,GlmPreTrainedModel:()=>rb,GptOssForCausalLM:()=>kb,GptOssModel:()=>Ob,GptOssPreTrainedModel:()=>Db,GraniteForCausalLM:()=>Rb,GraniteModel:()=>Lb,GraniteMoeHybridForCausalLM:()=>Vb,GraniteMoeHybridModel:()=>Bb,GraniteMoeHybridPreTrainedModel:()=>zb,GranitePreTrainedModel:()=>Ib,GraniteSpeechForConditionalGeneration:()=>Wb,GroundingDinoForObjectDetection:()=>Kb,GroundingDinoPreTrainedModel:()=>Gb,GroupViTModel:()=>Jb,GroupViTPreTrainedModel:()=>qb,HeliumForCausalLM:()=>Zb,HeliumModel:()=>Xb,HeliumPreTrainedModel:()=>Yb,HieraForImageClassification:()=>ex,HieraModel:()=>$b,HieraPreTrainedModel:()=>Qb,HubertForCTC:()=>cx,HubertForSequenceClassification:()=>lx,HubertModel:()=>sx,HubertPreTrainedModel:()=>ox,HunYuanDenseV1ForCausalLM:()=>fx,HunYuanDenseV1Model:()=>dx,HunYuanDenseV1PreTrainedModel:()=>ux,IJepaForImageClassification:()=>gx,IJepaModel:()=>hx,IJepaPreTrainedModel:()=>mx,Idefics3ForConditionalGeneration:()=>px,JAISLMHeadModel:()=>yx,JAISModel:()=>vx,JAISPreTrainedModel:()=>_x,JinaCLIPModel:()=>xx,JinaCLIPPreTrainedModel:()=>bx,JinaCLIPTextModel:()=>Sx,JinaCLIPVisionModel:()=>Cx,Lfm2ForCausalLM:()=>Ex,Lfm2Model:()=>Tx,Lfm2MoeForCausalLM:()=>Ax,Lfm2MoeModel:()=>kx,Lfm2MoePreTrainedModel:()=>Ox,Lfm2PreTrainedModel:()=>wx,Lfm2VlForConditionalGeneration:()=>jx,LightOnOcrForConditionalGeneration:()=>Dx,LiteWhisperForConditionalGeneration:()=>RD,Llama4ForCausalLM:()=>Ix,Llama4PreTrainedModel:()=>Fx,LlamaForCausalLM:()=>Px,LlamaModel:()=>Nx,LlamaPreTrainedModel:()=>Mx,LlavaForConditionalGeneration:()=>Gy,LlavaOnevisionForConditionalGeneration:()=>Gy,LlavaPreTrainedModel:()=>Wy,LlavaQwen2ForCausalLM:()=>qy,LongT5ForConditionalGeneration:()=>zx,LongT5Model:()=>Rx,LongT5PreTrainedModel:()=>Lx,M2M100ForConditionalGeneration:()=>Hx,M2M100Model:()=>Vx,M2M100PreTrainedModel:()=>Bx,MBartForCausalLM:()=>$x,MBartForConditionalGeneration:()=>Zx,MBartForSequenceClassification:()=>Qx,MBartModel:()=>Xx,MBartPreTrainedModel:()=>Yx,MPNetForMaskedLM:()=>cC,MPNetForQuestionAnswering:()=>dC,MPNetForSequenceClassification:()=>lC,MPNetForTokenClassification:()=>uC,MPNetModel:()=>sC,MPNetPreTrainedModel:()=>oC,MT5ForConditionalGeneration:()=>_C,MT5Model:()=>gC,MT5PreTrainedModel:()=>hC,MarianMTModel:()=>Gx,MarianModel:()=>Wx,MarianPreTrainedModel:()=>Ux,MaskFormerForInstanceSegmentation:()=>Jx,MaskFormerModel:()=>qx,MaskFormerPreTrainedModel:()=>Kx,Metric3DForDepthEstimation:()=>tS,Metric3DPreTrainedModel:()=>eS,Metric3Dv2ForDepthEstimation:()=>rS,Metric3Dv2PreTrainedModel:()=>nS,MgpstrForSceneTextRecognition:()=>oS,MgpstrModelOutput:()=>iS,MgpstrPreTrainedModel:()=>aS,MimiDecoderModel:()=>fS,MimiDecoderOutput:()=>cS,MimiEncoderModel:()=>dS,MimiEncoderOutput:()=>sS,MimiModel:()=>uS,MimiPreTrainedModel:()=>lS,Mistral4ForCausalLM:()=>vS,Mistral4Model:()=>_S,Mistral4PreTrainedModel:()=>gS,MistralForCausalLM:()=>hS,MistralModel:()=>mS,MistralPreTrainedModel:()=>pS,MobileBertForMaskedLM:()=>xS,MobileBertForQuestionAnswering:()=>CS,MobileBertForSequenceClassification:()=>SS,MobileBertModel:()=>bS,MobileBertPreTrainedModel:()=>yS,MobileLLMForCausalLM:()=>ES,MobileLLMModel:()=>TS,MobileLLMPreTrainedModel:()=>wS,MobileNetV1ForImageClassification:()=>kS,MobileNetV1ForSemanticSegmentation:()=>AS,MobileNetV1Model:()=>OS,MobileNetV1PreTrainedModel:()=>DS,MobileNetV2ForImageClassification:()=>NS,MobileNetV2ForSemanticSegmentation:()=>PS,MobileNetV2Model:()=>MS,MobileNetV2PreTrainedModel:()=>jS,MobileNetV3ForImageClassification:()=>LS,MobileNetV3ForSemanticSegmentation:()=>RS,MobileNetV3Model:()=>IS,MobileNetV3PreTrainedModel:()=>FS,MobileNetV4ForImageClassification:()=>VS,MobileNetV4ForSemanticSegmentation:()=>HS,MobileNetV4Model:()=>BS,MobileNetV4PreTrainedModel:()=>zS,MobileViTForImageClassification:()=>GS,MobileViTModel:()=>WS,MobileViTPreTrainedModel:()=>US,MobileViTV2ForImageClassification:()=>JS,MobileViTV2Model:()=>qS,MobileViTV2PreTrainedModel:()=>KS,ModernBertDecoderForCausalLM:()=>nC,ModernBertDecoderModel:()=>tC,ModernBertDecoderPreTrainedModel:()=>eC,ModernBertForMaskedLM:()=>ZS,ModernBertForSequenceClassification:()=>QS,ModernBertForTokenClassification:()=>$S,ModernBertModel:()=>XS,ModernBertPreTrainedModel:()=>YS,Moondream1ForConditionalGeneration:()=>Ky,MoonshineForConditionalGeneration:()=>aC,MoonshineModel:()=>iC,MoonshinePreTrainedModel:()=>rC,MptForCausalLM:()=>mC,MptModel:()=>pC,MptPreTrainedModel:()=>fC,MultiModalityCausalLM:()=>yC,MultiModalityPreTrainedModel:()=>vC,MusicgenForCausalLM:()=>SC,MusicgenForConditionalGeneration:()=>CC,MusicgenModel:()=>xC,MusicgenPreTrainedModel:()=>bC,NanoChatForCausalLM:()=>EC,NanoChatModel:()=>TC,NanoChatPreTrainedModel:()=>wC,NemotronHForCausalLM:()=>kC,NemotronHModel:()=>OC,NemotronHPreTrainedModel:()=>DC,NeoBertForMaskedLM:()=>MC,NeoBertForQuestionAnswering:()=>FC,NeoBertForSequenceClassification:()=>NC,NeoBertForTokenClassification:()=>PC,NeoBertModel:()=>jC,NeoBertPreTrainedModel:()=>AC,NomicBertModel:()=>LC,NomicBertPreTrainedModel:()=>IC,OPTForCausalLM:()=>tw,OPTModel:()=>ew,OPTPreTrainedModel:()=>$C,Olmo2ForCausalLM:()=>UC,Olmo2Model:()=>HC,Olmo2PreTrainedModel:()=>VC,Olmo3ForCausalLM:()=>KC,Olmo3Model:()=>GC,Olmo3PreTrainedModel:()=>WC,OlmoForCausalLM:()=>BC,OlmoHybridForCausalLM:()=>YC,OlmoHybridModel:()=>JC,OlmoHybridPreTrainedModel:()=>qC,OlmoModel:()=>zC,OlmoPreTrainedModel:()=>RC,OpenELMForCausalLM:()=>QC,OpenELMModel:()=>ZC,OpenELMPreTrainedModel:()=>XC,OwlViTForObjectDetection:()=>sw,OwlViTModel:()=>ow,OwlViTPreTrainedModel:()=>aw,Owlv2ForObjectDetection:()=>iw,Owlv2Model:()=>rw,Owlv2PreTrainedModel:()=>nw,PaliGemmaForConditionalGeneration:()=>cw,ParakeetForCTC:()=>uw,ParakeetPreTrainedModel:()=>lw,PatchTSMixerForPrediction:()=>pw,PatchTSMixerModel:()=>fw,PatchTSMixerPreTrainedModel:()=>dw,PatchTSTForPrediction:()=>gw,PatchTSTModel:()=>hw,PatchTSTPreTrainedModel:()=>mw,Phi3ForCausalLM:()=>Sw,Phi3Model:()=>xw,Phi3PreTrainedModel:()=>bw,Phi3VForCausalLM:()=>ww,Phi3VPreTrainedModel:()=>Cw,PhiForCausalLM:()=>yw,PhiModel:()=>vw,PhiPreTrainedModel:()=>_w,PreTrainedModel:()=>X,PvtForImageClassification:()=>Dw,PvtModel:()=>Ew,PvtPreTrainedModel:()=>Tw,PyAnnoteForAudioFrameClassification:()=>Aw,PyAnnoteModel:()=>kw,PyAnnotePreTrainedModel:()=>Ow,Qwen2ForCausalLM:()=>Nw,Qwen2Model:()=>Mw,Qwen2MoeForCausalLM:()=>Iw,Qwen2MoeModel:()=>Fw,Qwen2MoePreTrainedModel:()=>Pw,Qwen2PreTrainedModel:()=>jw,Qwen2VLForCausalLM:()=>db,Qwen2VLForConditionalGeneration:()=>ub,Qwen2VLPreTrainedModel:()=>lb,Qwen2_5_VLForCausalLM:()=>pb,Qwen2_5_VLForConditionalGeneration:()=>fb,Qwen3ForCausalLM:()=>zw,Qwen3Model:()=>Rw,Qwen3MoeForCausalLM:()=>Hw,Qwen3MoeModel:()=>Vw,Qwen3MoePreTrainedModel:()=>Bw,Qwen3NextForCausalLM:()=>Gw,Qwen3NextModel:()=>Ww,Qwen3NextPreTrainedModel:()=>Uw,Qwen3PreTrainedModel:()=>Lw,Qwen3VLForCausalLM:()=>qw,Qwen3VLForConditionalGeneration:()=>Kw,Qwen3VLMoeForCausalLM:()=>Yw,Qwen3VLMoeForConditionalGeneration:()=>Jw,Qwen3_5ForCausalLM:()=>Zw,Qwen3_5ForConditionalGeneration:()=>Xw,Qwen3_5MoeForCausalLM:()=>$w,Qwen3_5MoeForConditionalGeneration:()=>Qw,RFDetrForObjectDetection:()=>aT,RFDetrModel:()=>iT,RFDetrObjectDetectionOutput:()=>oT,RFDetrPreTrainedModel:()=>rT,RTDetrForObjectDetection:()=>J_,RTDetrModel:()=>q_,RTDetrObjectDetectionOutput:()=>Y_,RTDetrPreTrainedModel:()=>K_,RTDetrV2ForObjectDetection:()=>xT,RTDetrV2Model:()=>bT,RTDetrV2ObjectDetectionOutput:()=>ST,RTDetrV2PreTrainedModel:()=>yT,ResNetForImageClassification:()=>nT,ResNetModel:()=>tT,ResNetPreTrainedModel:()=>eT,RoFormerForMaskedLM:()=>hT,RoFormerForQuestionAnswering:()=>vT,RoFormerForSequenceClassification:()=>gT,RoFormerForTokenClassification:()=>_T,RoFormerModel:()=>mT,RoFormerPreTrainedModel:()=>pT,RobertaForMaskedLM:()=>lT,RobertaForQuestionAnswering:()=>fT,RobertaForSequenceClassification:()=>uT,RobertaForTokenClassification:()=>dT,RobertaModel:()=>cT,RobertaPreTrainedModel:()=>sT,Sam2ImageSegmentationOutput:()=>ET,Sam2Model:()=>OT,Sam2PreTrainedModel:()=>DT,Sam3TrackerModel:()=>AT,SamImageSegmentationOutput:()=>CT,SamModel:()=>TT,SamPreTrainedModel:()=>wT,SapiensForDepthEstimation:()=>NT,SapiensForNormalEstimation:()=>PT,SapiensForSemanticSegmentation:()=>MT,SapiensPreTrainedModel:()=>jT,SegformerForImageClassification:()=>LT,SegformerForSemanticSegmentation:()=>RT,SegformerModel:()=>IT,SegformerPreTrainedModel:()=>FT,SiglipModel:()=>BT,SiglipPreTrainedModel:()=>zT,SiglipTextModel:()=>VT,SiglipVisionModel:()=>HT,SmolLM3ForCausalLM:()=>GT,SmolLM3Model:()=>WT,SmolLM3PreTrainedModel:()=>UT,SmolVLMForConditionalGeneration:()=>KT,SnacDecoderModel:()=>XT,SnacEncoderModel:()=>YT,SnacModel:()=>JT,SnacPreTrainedModel:()=>qT,SolarOpenForCausalLM:()=>$T,SolarOpenModel:()=>QT,SolarOpenPreTrainedModel:()=>ZT,SpeechT5ForSpeechToText:()=>nE,SpeechT5ForTextToSpeech:()=>rE,SpeechT5HifiGan:()=>iE,SpeechT5Model:()=>tE,SpeechT5PreTrainedModel:()=>eE,SqueezeBertForMaskedLM:()=>sE,SqueezeBertForQuestionAnswering:()=>lE,SqueezeBertForSequenceClassification:()=>cE,SqueezeBertModel:()=>oE,SqueezeBertPreTrainedModel:()=>aE,StableLmForCausalLM:()=>fE,StableLmModel:()=>dE,StableLmPreTrainedModel:()=>uE,Starcoder2ForCausalLM:()=>hE,Starcoder2Model:()=>mE,Starcoder2PreTrainedModel:()=>pE,StyleTextToSpeech2Model:()=>_E,StyleTextToSpeech2PreTrainedModel:()=>gE,SupertonicForConditionalGeneration:()=>yE,SupertonicPreTrainedModel:()=>vE,Swin2SRForImageSuperResolution:()=>EE,Swin2SRModel:()=>TE,Swin2SRPreTrainedModel:()=>wE,SwinForImageClassification:()=>SE,SwinForSemanticSegmentation:()=>CE,SwinModel:()=>xE,SwinPreTrainedModel:()=>bE,T5ForConditionalGeneration:()=>kE,T5Model:()=>OE,T5PreTrainedModel:()=>DE,TableTransformerForObjectDetection:()=>ME,TableTransformerModel:()=>jE,TableTransformerObjectDetectionOutput:()=>NE,TableTransformerPreTrainedModel:()=>AE,TrOCRForCausalLM:()=>FE,TrOCRPreTrainedModel:()=>PE,UltravoxModel:()=>Ub,UltravoxPreTrainedModel:()=>Hb,UniSpeechForCTC:()=>RE,UniSpeechForSequenceClassification:()=>zE,UniSpeechModel:()=>LE,UniSpeechPreTrainedModel:()=>IE,UniSpeechSatForAudioFrameClassification:()=>WE,UniSpeechSatForCTC:()=>HE,UniSpeechSatForSequenceClassification:()=>UE,UniSpeechSatModel:()=>VE,UniSpeechSatPreTrainedModel:()=>BE,VaultGemmaForCausalLM:()=>qE,VaultGemmaModel:()=>KE,VaultGemmaPreTrainedModel:()=>GE,ViTForImageClassification:()=>ZE,ViTMAEModel:()=>$E,ViTMAEPreTrainedModel:()=>QE,ViTMSNForImageClassification:()=>nD,ViTMSNModel:()=>tD,ViTMSNPreTrainedModel:()=>eD,ViTModel:()=>XE,ViTPreTrainedModel:()=>YE,VisionEncoderDecoderModel:()=>JE,VitMatteForImageMatting:()=>iD,VitMattePreTrainedModel:()=>rD,VitPoseForPoseEstimation:()=>oD,VitPosePreTrainedModel:()=>aD,VitsModel:()=>lD,VitsModelOutput:()=>sD,VitsPreTrainedModel:()=>cD,VoxtralForConditionalGeneration:()=>uD,VoxtralRealtimeForConditionalGeneration:()=>bD,VoxtralRealtimePreTrainedModel:()=>yD,Wav2Vec2BertForCTC:()=>CD,Wav2Vec2BertForSequenceClassification:()=>wD,Wav2Vec2BertModel:()=>SD,Wav2Vec2BertPreTrainedModel:()=>xD,Wav2Vec2ForAudioFrameClassification:()=>ax,Wav2Vec2ForCTC:()=>rx,Wav2Vec2ForSequenceClassification:()=>ix,Wav2Vec2Model:()=>nx,Wav2Vec2PreTrainedModel:()=>tx,WavLMForAudioFrameClassification:()=>jD,WavLMForCTC:()=>OD,WavLMForSequenceClassification:()=>kD,WavLMForXVector:()=>AD,WavLMModel:()=>DD,WavLMPreTrainedModel:()=>ED,WeSpeakerResNetModel:()=>ND,WeSpeakerResNetPreTrainedModel:()=>MD,WhisperForConditionalGeneration:()=>LD,WhisperModel:()=>ID,WhisperPreTrainedModel:()=>FD,XLMForQuestionAnswering:()=>WD,XLMForSequenceClassification:()=>HD,XLMForTokenClassification:()=>UD,XLMModel:()=>BD,XLMPreTrainedModel:()=>zD,XLMRobertaForMaskedLM:()=>qD,XLMRobertaForQuestionAnswering:()=>XD,XLMRobertaForSequenceClassification:()=>JD,XLMRobertaForTokenClassification:()=>YD,XLMRobertaModel:()=>KD,XLMRobertaPreTrainedModel:()=>GD,XLMWithLMHeadModel:()=>VD,XVectorOutput:()=>TD,YolosForObjectDetection:()=>$D,YolosModel:()=>QD,YolosObjectDetectionOutput:()=>eO,YolosPreTrainedModel:()=>ZD,YoutuForCausalLM:()=>rO,YoutuModel:()=>nO,YoutuPreTrainedModel:()=>tO});var ug=class extends X{},dg=class extends ug{},fg=class extends ug{async _call(e){return new $m(await super._call(e))}},pg=class extends ug{async _call(e){return new nh(await super._call(e))}},mg=class extends ug{async _call(e){return new th(await super._call(e))}},hg=class extends X{},gg=class extends hg{},_g=class extends hg{},vg=class extends X{},yg=class extends vg{},bg=class extends vg{},xg=class extends X{},Sg=class extends xg{},Cg=class extends xg{},wg=class extends X{},Tg=class extends wg{},Eg=class extends wg{},Dg=class extends X{},Og=class extends Dg{},kg=class extends Dg{},Ag=class extends Dg{async _call(e){return new $m(await super._call(e))}},jg=class extends X{},Mg=class extends jg{},Ng=class extends jg{async _call(e){return new $m(await super._call(e))}},Pg=class extends X{},Fg=class extends Pg{},Ig=class extends Pg{async _call(e){return new th(await super._call(e))}},Lg=class extends Pg{async _call(e){return new $m(await super._call(e))}},Rg=class extends Pg{async _call(e){return new eh(await super._call(e))}},zg=class extends Pg{async _call(e){return new nh(await super._call(e))}},Bg=class extends X{},Vg=class extends Bg{},Hg=class extends Bg{},Ug=class extends X{},Wg=class extends Ug{},Gg=class extends Ug{},Kg=class extends X{},qg=class extends Kg{},Jg=class extends Kg{},Yg=class extends X{},Xg=class extends Yg{},Zg=class extends Yg{async _call(e){return new th(await super._call(e))}},Qg=class extends Yg{async _call(e){return new $m(await super._call(e))}},$g=class extends Yg{async _call(e){return new eh(await super._call(e))}},e_=class extends Yg{async _call(e){return new nh(await super._call(e))}},t_=4299n,n_=6561n,r_=class extends X{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`audio_values`,`exaggeration`,`audio_features`,`audio_tokens`,`speaker_embeddings`,`speaker_features`,`past_key_values`];main_input_name=`input_ids`;_return_dict_in_generate_keys=[`audio_tokens`,`speaker_embeddings`,`speaker_features`]},i_=class extends r_{async encode_speech(e){return Xm(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:n=null,exaggeration:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,audio_features:l=null,audio_tokens:u=null,speaker_embeddings:d=null,speaker_features:f=null,...p}){let m;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof q)){let t=e.dims[0];if(r==null)r=Al([t],.5);else if(typeof r==`number`)r=Al([t],r);else if(Array.isArray(r))r=new q(`float32`,r,[t]);else throw Error("Unsupported type for `exaggeration` input")}c.exaggeration=r}if(s.includes(`position_ids`)&&(c.position_ids=i),{inputs_embeds:a}=await Xm(this.sessions.embed_tokens,c),l&&u&&d&&f&&(m={audio_features:l,audio_tokens:u,speaker_embeddings:d,speaker_features:f}),m||n)m??=await this.encode_speech(n),a=Cl([m.audio_features,a],1),t=Ml([a.dims[0],a.dims[1]]);else{let e=a.dims[1];if(!o||e!==1)throw Error(`Incorrect state encountered during generation.`);let n=o.get_seq_length();t=Ml([a.dims[0],n+e])}}return{...await Xh(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c},!1),...m}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.input_ids.dims[1]===1?t.position_ids=new q(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==n_)-1),[e.length,1]):t.position_ids=new q(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=n_?0:t++)}).flat(),t.input_ids.dims)),t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),ng(this,e,t,n)}async generate(e){let{sequences:t,audio_tokens:n,speaker_embeddings:r,speaker_features:i}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=Cl([n,a,Al([a.dims[0],3],t_)],1),{waveform:s}=await Xm(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:i,speaker_embeddings:r});return s}},a_=class extends X{},o_=class extends a_{},s_=class extends X{},c_=class extends s_{},l_=class extends X{},u_=class extends l_{},d_=class extends l_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},f_=class extends l_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},p_=class extends X{},m_=class extends p_{},h_=class extends p_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},g_=class extends p_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},__=class extends p_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},v_=class extends p_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},y_=class extends X{},b_=class extends y_{},x_=class extends y_{},S_=class extends X{},C_=class extends S_{},w_=class extends S_{},T_=class extends X{},E_=class extends T_{},D_=class extends T_{},O_=class extends X{},k_=class extends O_{},A_=class extends O_{},j_=class extends X{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},M_=class extends j_{},N_=class extends j_{},P_=class extends X{},F_=class extends P_{},I_=class extends P_{async _call(e){return new th(await super._call(e))}},L_=class extends P_{async _call(e){return new $m(await super._call(e))}},R_=class extends P_{async _call(e){return new eh(await super._call(e))}},z_=class extends P_{async _call(e){return new nh(await super._call(e))}},B_=class extends X{},V_=class extends B_{},H_=class extends B_{async _call(e){return new $m(await super._call(e))}},U_=class extends X{},W_=class extends U_{},G_=class extends U_{async _call(e){return new $m(await super._call(e))}},K_=class extends X{},q_=class extends K_{},J_=class extends K_{async _call(e){return new Y_(await super._call(e))}},Y_=class extends Qm{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},X_=class extends X{},Z_=class extends X_{},Q_=class extends X_{async _call(e){return new Y_(await super._call(e))}},$_=class extends Qm{constructor({audio_codes:e}){super(),this.audio_codes=e}},ev=class extends Qm{constructor({audio_values:e}){super(),this.audio_values=e}},tv=class extends X{main_input_name=`input_values`;forward_params=[`input_values`]},nv=class extends tv{async encode(e){return new $_(await Xm(this.sessions.encoder_model,e))}async decode(e){return new ev(await Xm(this.sessions.decoder_model,e))}},rv=class extends tv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},iv=class extends tv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},av=class extends X{},ov=class extends av{},sv=class extends av{async _call(e){return new th(await super._call(e))}},cv=class extends av{async _call(e){return new $m(await super._call(e))}},lv=class extends av{async _call(e){return new eh(await super._call(e))}},uv=class extends av{async _call(e){return new nh(await super._call(e))}},dv=class extends X{},fv=class extends dv{},pv=class extends dv{},mv=class extends X{},hv=class extends mv{},gv=class extends mv{async _call(e){return new th(await super._call(e))}},_v=class extends mv{async _call(e){return new $m(await super._call(e))}},vv=class extends mv{async _call(e){return new eh(await super._call(e))}},yv=class extends mv{async _call(e){return new nh(await super._call(e))}},bv=class extends X{},xv=class extends bv{},Sv=class extends X{},Cv=class extends Sv{},wv=class extends Sv{async _call(e){return new $m(await super._call(e))}},Tv=class extends X{},Ev=class extends Tv{},Dv=class extends X{},Ov=class extends Dv{},kv=class extends X{},Av=class extends kv{},jv=class extends kv{async _call(e){return new Nv(await super._call(e))}},Mv=class extends kv{async _call(e){return new Pv(await super._call(e))}},Nv=class extends Qm{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Pv=class extends Qm{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},Fv=class extends X{},Iv=class extends Fv{},Lv=class extends Fv{async _call(e){return new $m(await super._call(e))}},Rv=class extends X{},zv=class extends Rv{},Bv=class extends Rv{async _call(e){return new $m(await super._call(e))}},Vv=class extends X{},Hv=class extends Vv{},Uv=class extends X{},Wv=class extends Uv{},Gv=class extends X{},Kv=class extends Gv{},qv=class extends Gv{async _call(e){return new $m(await super._call(e))}},Jv=class extends Gv{async _call(e){return new eh(await super._call(e))}},Yv=class extends Gv{async _call(e){return new nh(await super._call(e))}},Xv=class extends Gv{async _call(e){return new th(await super._call(e))}},Zv=class extends X{},Qv=class extends Zv{},$v=class extends X{},ey=class extends $v{},ty=class extends $v{},ny=class extends X{},ry=class extends ny{},iy=class extends ny{async _call(e){return new $m(await super._call(e))}},ay=class extends X{},oy=class extends ay{},sy=class extends ay{async _call(e){return new th(await super._call(e))}},cy=class extends ay{async _call(e){return new $m(await super._call(e))}},ly=class extends ay{async _call(e){return new eh(await super._call(e))}},uy=class extends ay{async _call(e){return new nh(await super._call(e))}},dy=class extends X{},fy=class extends dy{},py=class extends dy{},my=class extends X{},hy=class extends my{},gy=class extends my{async _call(e){return new th(await super._call(e))}},_y=class extends my{async _call(e){return new $m(await super._call(e))}},vy=class extends my{async _call(e){return new eh(await super._call(e))}},yy=class extends X{},by=class extends yy{},xy=class extends yy{async _call(e){return new th(await super._call(e))}},Sy=class extends yy{async _call(e){return new $m(await super._call(e))}},Cy=class extends yy{async _call(e){return new eh(await super._call(e))}},wy=class extends X{},Ty=class extends wy{},Ey=class extends wy{},Dy=class extends X{},Oy=class extends Dy{},ky=class extends Dy{},Ay=class extends X{},jy=class extends Ay{},My=class extends Ay{},Ny=class extends X{},Py=class extends Ny{},Fy=class extends Ny{async _call(e){return new $m(await super._call(e))}},Iy=class extends X{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`pixel_values`,`encoder_outputs`,`decoder_input_ids`,`decoder_inputs_embeds`,`decoder_attention_mask`,`past_key_values`];main_input_name=`inputs_embeds`},Ly=class extends Iy{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:Cl([t,e],1),attention_mask:Cl([Ml(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:n,attention_mask:r}){if(!e&&!t)throw Error("Either `input_ids` or `pixel_values` should be provided.");let i,a;return e&&(i=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),i&&a?{inputs_embeds:n,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:i,image_features:a,input_ids:e,attention_mask:r}):n=i||a,{inputs_embeds:n,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:n,decoder_input_ids:r,decoder_attention_mask:i,encoder_outputs:a,past_key_values:o,inputs_embeds:s,decoder_inputs_embeds:c}){if(s||({inputs_embeds:s,attention_mask:n}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n})),!a){let{last_hidden_state:e}=await Gh(this,{inputs_embeds:s,attention_mask:n});a=e}if(!c){if(!r)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:r})}return await Xh(this,{inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o},!0)}},Ry=class extends X{},zy=class extends Ry{},By=class extends Ry{},Vy=class extends X{},Hy=class extends Vy{},Uy=class extends Vy{},Wy=class extends X{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},Gy=class extends Wy{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return og({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},Ky=class extends Gy{},qy=class extends Gy{},Jy=class extends X{},Yy=class extends Jy{},Xy=class extends Gy{},Zy=class extends Xy{},Qy=class extends X{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`input_features`,`input_features_mask`,`past_key_values`]},$y=class extends Qy{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,input_features:r=null,input_features_mask:i=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:s=null,past_key_values:c=null,generation_config:l=null,logits_processor:u=null,...d}){if((!o||!s)&&({inputs_embeds:o,per_layer_inputs:s}=await Xm(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(n){let{image_features:r}=await this._encode_vision({pixel_values:n,...d});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:r,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){let{audio_features:n}=await Xm(this.sessions.audio_encoder,{input_features:r,input_features_mask:i});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:n,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await Xh(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u},!0)}_encode_vision(e){return Xm(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return og({image_token_id:this.config.image_token_id,...e,image_features:n})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return sg({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},eb=class extends $y{},tb=class extends $y{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`image_position_ids`,`input_features`,`input_features_mask`,`past_key_values`];_encode_vision(e){return Xm(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},nb=class extends tb{},rb=class extends X{},ib=class extends rb{},ab=class extends rb{},ob=class extends X{},sb=class extends ob{},cb=class extends ob{},lb=class extends X{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},ub=class extends lb{image_grid_thw_name=`grid_thw`;_get_text_only_rope_index(e,t){if(t){let{data:e,dims:n}=eg(t),r=BigInt64Array.from({length:3*e.length},(t,n)=>e[n%e.length]),i=Array.from({length:n[0]},(t,r)=>bc(e.subarray(n[1]*r,n[1]*(r+1)))[0]+1n+BigInt(n[1]));return[new q(`int64`,r,[3,...n]),new q(`int64`,i,[i.length,1])]}else{let[t,n]=e.dims;return[new q(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),Pl([t,1])]}}_reorder_and_write_positions(e,t,n,r){let i=e.reduce((e,t)=>e+t.length,0),a=Array(i),o=0;for(let t=0;t<3;++t)for(let n of e){let e=n.length/3;for(let r=t*e;r<(t+1)*e;++r)a[o++]=n[r]}let s=0;for(let e=0;e(t==s&&e.push(n),e),[]).map(e=>c[e+1]),u=l.filter(e=>e==a).length,d=l.filter(e=>e==o).length,f=[],p=0,m=u,h=d;for(let e=0;et>p&&e==a),s=c.findIndex((e,t)=>t>p&&e==o),l=m>0&&e!==-1?e:c.length+1,u=h>0&&s!==-1?s:c.length+1,d,g,_,v;l0?bc(f.at(-1))[0]+1:0;f.push(Array.from({length:3*S},(e,t)=>C+t%S));let w=S+C,T=y*b*x,E=Array.from({length:T},(e,t)=>w+Math.floor(t/(b*x))),D=Array.from({length:T},(e,t)=>w+Math.floor(t/x)%b),O=Array.from({length:T},(e,t)=>w+t%x);f.push([E,D,O].flat()),p=d+T}if(p0?bc(f.at(-1))[0]+1:0,t=c.length-p;f.push(Array.from({length:3*t},(n,r)=>e+r%t))}return f}get_rope_index(e,t,n,r){let{vision_config:i}=this.config,a=i.spatial_merge_size??2;if(t||n){let i=e.tolist();r||=Nl(e);let o=r.tolist(),s=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],l=n?n.tolist():[],u={image_index:0,video_index:0},d=[];for(let e=0;eo[e][n]==1),n=this._get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:c,video_grid_thw_list:l,spatial_merge_size:a,state:u}),r=this._reorder_and_write_positions(n,o[e],s,e);d.push(bc(r)[0]+1-i[e].length)}return[new q(`int64`,s.flat(1/0),[3,e.dims[0],e.dims[1]]),new q(`int64`,d,[d.length,1])]}else return this._get_text_only_rope_index(e,r)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await Xm(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return og({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes(`position_ids`))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(en+e);t.position_ids=wl([r,r,r],0)}}return t}},db=class extends ub{},fb=class extends ub{image_grid_thw_name=`image_grid_thw`},pb=class extends db{image_grid_thw_name=`image_grid_thw`},mb=class extends fb{get_vision_position_ids(e,t,n,r){let i=Math.floor(t[0]/n),a=Math.floor(t[1]/r),o=Math.floor(t[2]/r),s=a*o*i,c=Array.from({length:s},()=>e),l=Array.from({length:s},(t,n)=>e+Math.floor(n/(o*i))),u=Array.from({length:s},(t,n)=>e+n%o);return[...c,...l,...u]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a}=this.config,o=[],s=0,c=+(e[0]==a);for(let t=1;t<=e.length;++t){let n=tl+n%e)),l+=e}else{let e=t[i.image_index++].map(Number),n=e[0];u.push(this.get_vision_position_ids(l,e,n,r)),l+=Math.max(e[1],e[2])/r}return u}},hb=class extends X{},gb=class extends hb{},_b=class extends hb{},vb=class extends X{},yb=class extends vb{},bb=class extends vb{},xb=class extends X{},Sb=class extends xb{},Cb=class extends xb{},wb=class extends X{},Tb=class extends wb{},Eb=class extends wb{},Db=class extends X{},Ob=class extends Db{},kb=class extends Db{},Ab=class extends X{},jb=class extends Ab{},Mb=class extends Ab{},Nb=class extends X{},Pb=class extends Nb{},Fb=class extends Nb{},Ib=class extends X{},Lb=class extends Ib{},Rb=class extends Ib{},zb=class extends X{},Bb=class extends zb{},Vb=class extends zb{},Hb=class extends X{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},Ub=class extends Hb{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return sg({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},Wb=class extends Ub{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},Gb=class extends X{},Kb=class extends Gb{},qb=class extends X{},Jb=class extends qb{},Yb=class extends X{},Xb=class extends Yb{},Zb=class extends Yb{},Qb=class extends X{},$b=class extends Qb{},ex=class extends Qb{async _call(e){return new $m(await super._call(e))}},tx=class extends X{},nx=class extends tx{},rx=class extends tx{async _call(e){return new rh(await super._call(e))}},ix=class extends tx{async _call(e){return new $m(await super._call(e))}},ax=class extends tx{async _call(e){return new eh(await super._call(e))}},ox=class extends X{},sx=class extends tx{},cx=class extends tx{async _call(e){return new rh(await super._call(e))}},lx=class extends tx{async _call(e){return new $m(await super._call(e))}},ux=class extends X{},dx=class extends ux{},fx=class extends ux{},px=class extends Gy{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},mx=class extends X{},hx=class extends mx{},gx=class extends mx{async _call(e){return new $m(await super._call(e))}},_x=class extends X{},vx=class extends _x{},yx=class extends _x{},bx=class extends X{},xx=class extends bx{async forward(e){let t=!e.input_ids,n=!e.pixel_values;if(t&&n)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=Ml([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=Al([0,3,t,t],0)}let{text_embeddings:r,image_embeddings:i,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),s={};return t||(s.text_embeddings=r,s.l2norm_text_embeddings=a),n||(s.image_embeddings=i,s.l2norm_image_embeddings=o),s}},Sx=class extends bx{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Cx=class extends bx{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},wx=class extends X{},Tx=class extends wx{},Ex=class extends wx{},Dx=class extends Gy{},Ox=class extends X{},kx=class extends Ox{},Ax=class extends Ox{},jx=class extends Gy{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},Mx=class extends X{},Nx=class extends Mx{},Px=class extends Mx{},Fx=class extends X{},Ix=class extends Fx{},Lx=class extends X{},Rx=class extends Lx{},zx=class extends Lx{},Bx=class extends X{},Vx=class extends Bx{},Hx=class extends Bx{},Ux=class extends X{},Wx=class extends Ux{},Gx=class extends Ux{},Kx=class extends X{},qx=class extends Kx{},Jx=class extends Kx{},Yx=class extends X{},Xx=class extends Yx{},Zx=class extends Yx{},Qx=class extends Yx{async _call(e){return new $m(await super._call(e))}},$x=class extends Yx{},eS=class extends X{},tS=class extends eS{},nS=class extends X{},rS=class extends nS{},iS=class extends Qm{constructor({char_logits:e,bpe_logits:t,wp_logits:n}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=n}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},aS=class extends X{},oS=class extends aS{async _call(e){return new iS(await super._call(e))}},sS=class extends Qm{constructor({audio_codes:e}){super(),this.audio_codes=e}},cS=class extends Qm{constructor({audio_values:e}){super(),this.audio_values=e}},lS=class extends X{main_input_name=`input_values`;forward_params=[`input_values`]},uS=class extends lS{async encode(e){return new sS(await Xm(this.sessions.encoder_model,e))}async decode(e){return new cS(await Xm(this.sessions.decoder_model,e))}},dS=class extends lS{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},fS=class extends lS{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},pS=class extends X{},mS=class extends pS{},hS=class extends pS{},gS=class extends X{},_S=class extends gS{},vS=class extends gS{},yS=class extends X{},bS=class extends yS{},xS=class extends yS{async _call(e){return new th(await super._call(e))}},SS=class extends yS{async _call(e){return new $m(await super._call(e))}},CS=class extends yS{async _call(e){return new nh(await super._call(e))}},wS=class extends X{},TS=class extends wS{},ES=class extends wS{},DS=class extends X{},OS=class extends DS{},kS=class extends DS{async _call(e){return new $m(await super._call(e))}},AS=class extends DS{},jS=class extends X{},MS=class extends jS{},NS=class extends jS{async _call(e){return new $m(await super._call(e))}},PS=class extends jS{},FS=class extends X{},IS=class extends FS{},LS=class extends FS{async _call(e){return new $m(await super._call(e))}},RS=class extends FS{},zS=class extends X{},BS=class extends zS{},VS=class extends zS{async _call(e){return new $m(await super._call(e))}},HS=class extends zS{},US=class extends X{},WS=class extends US{},GS=class extends US{async _call(e){return new $m(await super._call(e))}},KS=class extends X{},qS=class extends KS{},JS=class extends KS{async _call(e){return new $m(await super._call(e))}},YS=class extends X{},XS=class extends YS{},ZS=class extends YS{async _call(e){return new th(await super._call(e))}},QS=class extends YS{async _call(e){return new $m(await super._call(e))}},$S=class extends YS{async _call(e){return new eh(await super._call(e))}},eC=class extends X{},tC=class extends eC{},nC=class extends eC{},rC=class extends X{requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},iC=class extends rC{},aC=class extends rC{},oC=class extends X{},sC=class extends oC{},cC=class extends oC{async _call(e){return new th(await super._call(e))}},lC=class extends oC{async _call(e){return new $m(await super._call(e))}},uC=class extends oC{async _call(e){return new eh(await super._call(e))}},dC=class extends oC{async _call(e){return new nh(await super._call(e))}},fC=class extends X{},pC=class extends fC{},mC=class extends fC{},hC=class extends X{},gC=class extends hC{},_C=class extends hC{},vC=class extends X{},yC=class extends vC{forward_params=[`input_ids`,`pixel_values`,`images_seq_mask`,`images_emb_mask`,`attention_mask`,`position_ids`,`past_key_values`];constructor(...e){super(...e),this._generation_mode=`text`}async forward(e){let t=this._generation_mode??`text`,n;if(t===`text`||!e.past_key_values){let t=this.sessions.prepare_inputs_embeds;n=await Xm(t,vi(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await Xm(t,vi({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await Xh(this,r),a=this.sessions[t===`text`?`lm_head`:`gen_head`];if(!a)throw Error(`Unable to find "${a}" generation head`);let o=await Xm(a,vi(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=Cl([t.input_ids,t.input_ids],0):(t.input_ids=Cl([t.input_ids,jl(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=Cl([t.attention_mask,jl(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=Al([0,0,3,384,384],1)),r&&(t.images_seq_mask=new q(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new q(`bool`,[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode=`text`,super.generate(e)}async generate_images(e){this._generation_mode=`image`;let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),r=this.sessions.image_decode,{decoded_image:i}=await Xm(r,{generated_tokens:n}),a=i.add_(1).mul_(255/2).clamp_(0,255).to(`uint8`),o=[];for(let e of a){let t=nf.fromTensor(e);o.push(t)}return o}},bC=class extends X{},xC=class extends bC{},SC=class extends bC{},CC=class extends X{forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`];_apply_and_filter_by_delay_pattern_mask(e){let[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r,a=0;for(let t=0;t0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new q(e.type,e.data.slice(0,a),[o,r,s])}prepare_inputs_for_generation(e,t,n){let r=BigInt(this.config.decoder.pad_token_id),i=structuredClone(e);for(let e=0;e=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),rg(this,i,t,n)}async generate(e){let t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await Xm(this.sessions.encodec_decode,{audio_codes:n});return r}},wC=class extends X{},TC=class extends wC{},EC=class extends wC{},DC=class extends X{},OC=class extends DC{},kC=class extends DC{},AC=class extends X{},jC=class extends AC{},MC=class extends AC{async _call(e){return new th(await super._call(e))}},NC=class extends AC{async _call(e){return new $m(await super._call(e))}},PC=class extends AC{async _call(e){return new eh(await super._call(e))}},FC=class extends AC{async _call(e){return new nh(await super._call(e))}},IC=class extends X{},LC=class extends IC{},RC=class extends X{},zC=class extends RC{},BC=class extends RC{},VC=class extends X{},HC=class extends VC{},UC=class extends VC{},WC=class extends X{},GC=class extends WC{},KC=class extends WC{},qC=class extends X{},JC=class extends qC{},YC=class extends qC{},XC=class extends X{},ZC=class extends XC{},QC=class extends XC{},$C=class extends X{},ew=class extends $C{},tw=class extends $C{},nw=class extends X{},rw=class extends nw{},iw=class extends nw{},aw=class extends X{},ow=class extends aw{},sw=class extends aw{},cw=class extends Gy{},lw=class extends X{},uw=class extends lw{async _call(e){return new rh(await super._call(e))}},dw=class extends X{},fw=class extends dw{},pw=class extends dw{},mw=class extends X{},hw=class extends mw{},gw=class extends mw{},_w=class extends X{},vw=class extends _w{},yw=class extends _w{},bw=class extends X{},xw=class extends bw{},Sw=class extends bw{},Cw=class extends X{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},ww=class extends Cw{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,image_sizes:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,...l}){if(!a){let t;if(n&&e.dims[1]!==1){if(!r)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await Xm(this.sessions.vision_encoder,{pixel_values:n,image_sizes:r}))}else{let e=this.config.normalized_config.hidden_size;t=new q(`float32`,[],[0,e])}({inputs_embeds:a}=await Xm(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await Xh(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c},!1)}},Tw=class extends X{},Ew=class extends Tw{},Dw=class extends Tw{async _call(e){return new $m(await super._call(e))}},Ow=class extends X{},kw=class extends Ow{},Aw=class extends Ow{async _call(e){return new eh(await super._call(e))}},jw=class extends X{},Mw=class extends jw{},Nw=class extends jw{},Pw=class extends X{},Fw=class extends Pw{},Iw=class extends Pw{},Lw=class extends X{},Rw=class extends Lw{},zw=class extends Lw{},Bw=class extends X{},Vw=class extends Bw{},Hw=class extends Bw{},Uw=class extends X{},Ww=class extends Uw{},Gw=class extends Uw{},Kw=class extends fb{},qw=class extends pb{},Jw=class extends Kw{},Yw=class extends qw{},Xw=class extends Kw{},Zw=class extends Xw{},Qw=class extends Xw{},$w=class extends Zw{},eT=class extends X{},tT=class extends eT{},nT=class extends eT{async _call(e){return new $m(await super._call(e))}},rT=class extends X{},iT=class extends rT{},aT=class extends rT{async _call(e){return new oT(await super._call(e))}},oT=class extends Y_{},sT=class extends X{},cT=class extends sT{},lT=class extends sT{async _call(e){return new th(await super._call(e))}},uT=class extends sT{async _call(e){return new $m(await super._call(e))}},dT=class extends sT{async _call(e){return new eh(await super._call(e))}},fT=class extends sT{async _call(e){return new nh(await super._call(e))}},pT=class extends X{},mT=class extends pT{},hT=class extends pT{async _call(e){return new th(await super._call(e))}},gT=class extends pT{async _call(e){return new $m(await super._call(e))}},_T=class extends pT{async _call(e){return new eh(await super._call(e))}},vT=class extends pT{async _call(e){return new nh(await super._call(e))}},yT=class extends X{},bT=class extends yT{},xT=class extends yT{async _call(e){return new ST(await super._call(e))}},ST=class extends Y_{},CT=class extends Qm{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},wT=class extends X{},TT=class extends wT{async get_image_embeddings({pixel_values:e}){return await Gh(this,{pixel_values:e})}async forward(e){e=!e.image_embeddings||!e.image_positional_embeddings?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_labels??=Ml(e.input_points.dims.slice(0,-1));let 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 Xm(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new CT(await super._call(e))}},ET=class extends Qm{constructor({iou_scores:e,pred_masks:t,object_score_logits:n}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=n}},DT=class extends X{},OT=class extends DT{async get_image_embeddings({pixel_values:e}){return await Gh(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let t=e.input_points.dims;e.input_labels??=Ml(t.slice(0,-1)),e.input_boxes??=Al([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=Al([t[0],t[1],0],-1n),e.input_points=Al([t[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder;return await Xm(n,vi(e,n.inputNames))}async _call(e){return new ET(await super._call(e))}},kT=class extends OT{},AT=class extends OT{},jT=class extends X{},MT=class extends jT{},NT=class extends jT{},PT=class extends jT{},FT=class extends X{},IT=class extends FT{},LT=class extends FT{},RT=class extends FT{},zT=class extends X{},BT=class extends zT{},VT=class extends zT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},HT=class extends p_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},UT=class extends X{},WT=class extends UT{},GT=class extends UT{},KT=class extends px{},qT=class extends X{main_input_name=`input_values`;forward_params=[`input_values`]},JT=class extends qT{async encode(e){return await Xm(this.sessions.encoder_model,e)}async decode(e){return await Xm(this.sessions.decoder_model,e)}},YT=class extends qT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},XT=class extends qT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},ZT=class extends X{},QT=class extends ZT{},$T=class extends ZT{},eE=class extends X{},tE=class extends eE{},nE=class extends eE{},rE=class extends eE{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let{encoder_outputs:o,encoder_attention_mask:s}=await Gh(this,{input_ids:e}),c=o.dims[1]/this.config.reduction_factor,l=Math.floor(c*i),u=Math.floor(c*r),d=this.config.num_mel_bins,f=[],p=null,m=null,h=0;for(;;){++h;let e=Rh(!!m),r;r=m?m.output_sequence_out:new q(`float32`,new Float32Array(d),[1,1,d]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:s,speaker_embeddings:t,encoder_hidden_states:o};Yh(this,i,p),m=await Xm(this.sessions.decoder_model_merged,i),p=qh(m,p);let{prob:a,spectrum:c}=m;if(f.push(c),h>=u&&(Array.from(a.data).filter(e=>e>=n).length>0||h>=l))break}let g=Cl(f),{waveform:_}=await Xm(a.sessions.model,{spectrogram:g});return{spectrogram:g,waveform:_}}},iE=class extends X{main_input_name=`spectrogram`},aE=class extends X{},oE=class extends aE{},sE=class extends aE{async _call(e){return new th(await super._call(e))}},cE=class extends aE{async _call(e){return new $m(await super._call(e))}},lE=class extends aE{async _call(e){return new nh(await super._call(e))}},uE=class extends X{},dE=class extends uE{},fE=class extends uE{},pE=class extends X{},mE=class extends pE{},hE=class extends pE{},gE=class extends X{},_E=class extends gE{},vE=class extends X{},yE=class extends vE{async generate_speech({input_ids:e,attention_mask:t,style:n,num_inference_steps:r=5,speed:i=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:s,latent_dim:c}=this.config,{last_hidden_state:l,durations:u}=await Xm(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:n}),d=u.div(i).mul_(a),f=s*o,p=d.data,m=Int32Array.from(p,e=>Math.ceil(e/f)),h=Math.max(...m),g=e.dims[0],_=new BigInt64Array(g*h);for(let e=0;ee*t,1)),d[e]);let f=new q(l,new u(s*dD),[1,s,dD]),p=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!p)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:f,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:p,text_hidden_size:n.hidden_size}}async function hD(e,t){let n=t.dims[2],r=Math.floor((fD+n-3)/2)+1,i=new q(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=Ml([1,a]),{audio_embeds:s,present_padding_cache:c,...l}=await Xm(e.encoder_session,{input_features:t,attention_mask:o,position_ids:i,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location===`gpu-buffer`&&e.enc_padding_cache.dispose(),e.enc_padding_cache=c;for(let t in l)if(t.startsWith(`present.`)){let n=t.replace(`present`,`past_key_values`),r=e.enc_kv_cache[n];r?.location===`gpu-buffer`&&r.dispose(),e.enc_kv_cache[n]=l[t]}return e.enc_past_seq_len=a,s}async function gD(e,t){for(;e.audio_embed_total_tokens0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],n=t.tokens-e.audio_queue_offset,o=Math.min(a,n),s=e.audio_queue_offset*e.text_hidden_size;for(let n=0;n=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var vD=class extends xh{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},yD=class extends X{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},bD=class extends yD{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=pD.get(this);i&&await gD(i,i.audio_consumed+r);let{inputs_embeds:a}=await Xm(this.sessions.embed_tokens,{input_ids:e});i&&_D(i,a,r);let o={inputs_embeds:a,...n};Yh(this,o,t);let s=this.sessions.decoder_model_merged;return await Xm(s,vi(o,s.inputNames))}async generate({input_features:e,stopping_criteria:t,...n}){if(!e)throw Error(`input_features (generator/iterable) must be provided`);let r=mD(this,e);pD.set(this,r);let i=new Sh;i.push(new vD(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),pD.delete(this)}}},xD=class extends X{},SD=class extends xD{},CD=class extends xD{async _call(e){return new rh(await super._call(e))}},wD=class extends xD{async _call(e){return new $m(await super._call(e))}},TD=class extends Qm{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},ED=class extends X{},DD=class extends ED{},OD=class extends ED{async _call(e){return new rh(await super._call(e))}},kD=class extends ED{async _call(e){return new $m(await super._call(e))}},AD=class extends ED{async _call(e){return new TD(await super._call(e))}},jD=class extends ED{async _call(e){return new eh(await super._call(e))}},MD=class extends X{},ND=class extends MD{},PD=class extends bh{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},FD=class extends X{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`attention_mask`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},ID=class extends FD{},LD=class extends FD{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,PD)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(V.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${Bu(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??`transcribe`])}else if(n||r)throw 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&&(V.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(e=>e!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);let a=i.decoder_input_ids instanceof q?Bl(i.decoder_input_ids):i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new sh,n.push(new fh(t,a))),t.begin_suppress_tokens&&(n??=new sh,n.push(new dh(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task===`translate`&&V.warn(`Token-level timestamps may not be reliable for task 'translate'.`),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!i.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:a,kwargs:i});let o=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:r,kwargs:i}){let a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,s=t.return_token_timestamps,c=e,l=c.dims[2],u=2*this.config.max_source_positions,d=0,f=[],p=[];for(;de+n)}if(v.length>0&&v.at(-1)===o&&v.pop(),v.length===0)break;let b=v.map(e=>e>=a),x=v.length>=2&&b[v.length-1]&&!b[v.length-2],S=[];for(let e=0;e0)if(x)C=e-d;else{let e=S.at(-1);C=(v[e-1]-a)*2,w=e}else C=e-d;let T=Math.floor(d/2),E=a+1500;for(let e=0;e=a&&(v[e]=Math.min(v[e]+T,E));f.push(...v.slice(0,w)),y&&p.push(...y.slice(0,w)),d+=C}f.push(o);let m=[...r,...f];if(s){let e=new q(`int64`,m.map(BigInt),[1,m.length]),t=[...Array(r.length).fill(0),...p,0];return{sequences:e,token_timestamps:new q(`float32`,new Float32Array(t),[1,t.length])}}return new q(`int64`,m.map(BigInt),[1,m.length])}_extract_token_timestamps(e,t,n=null,r=.02,i=0){if(!e.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");n??V.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(V.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let o=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},(e,t)=>Cl(o.map(e=>e[t]),2)),c=wl(t.map(([e,t])=>{if(e>=s.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)})).transpose(1,0,2,3),[l,u]=El(c,-2,0,!0),d=c.clone();for(let e=0;e0?d.slice(null,null,[i,d.dims[2]],null):d,1)],p=e.sequences.dims,m=new q(`float32`,new Float32Array(p[0]*p[1]),p);for(let e=0;et[n+1]-t[n])).map(e=>!!e),o=[];for(let e=0;e0&&s.push(o.at(-1)),m[e].data.set(s)}return m}},RD=class extends LD{},zD=class extends X{},BD=class extends zD{},VD=class extends zD{async _call(e){return new th(await super._call(e))}},HD=class extends zD{async _call(e){return new $m(await super._call(e))}},UD=class extends zD{async _call(e){return new eh(await super._call(e))}},WD=class extends zD{async _call(e){return new nh(await super._call(e))}},GD=class extends X{},KD=class extends GD{},qD=class extends GD{async _call(e){return new th(await super._call(e))}},JD=class extends GD{async _call(e){return new $m(await super._call(e))}},YD=class extends GD{async _call(e){return new eh(await super._call(e))}},XD=class extends GD{async _call(e){return new nh(await super._call(e))}},ZD=class extends X{},QD=class extends ZD{},$D=class extends ZD{async _call(e){return new eO(await super._call(e))}},eO=class extends Qm{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},tO=class extends X{},nO=class extends tO{},rO=class extends tO{},iO=new Map([[`bert`,`BertModel`],[`eurobert`,`EuroBertModel`],[`neobert`,`NeoBertModel`],[`modernbert`,`ModernBertModel`],[`nomic_bert`,`NomicBertModel`],[`roformer`,`RoFormerModel`],[`electra`,`ElectraModel`],[`esm`,`EsmModel`],[`convbert`,`ConvBertModel`],[`camembert`,`CamembertModel`],[`deberta`,`DebertaModel`],[`deberta-v2`,`DebertaV2Model`],[`mpnet`,`MPNetModel`],[`albert`,`AlbertModel`],[`distilbert`,`DistilBertModel`],[`roberta`,`RobertaModel`],[`xlm`,`XLMModel`],[`xlm-roberta`,`XLMRobertaModel`],[`clap`,`ClapModel`],[`clip`,`CLIPModel`],[`clipseg`,`CLIPSegModel`],[`chinese_clip`,`ChineseCLIPModel`],[`siglip`,`SiglipModel`],[`jina_clip`,`JinaCLIPModel`],[`mobilebert`,`MobileBertModel`],[`squeezebert`,`SqueezeBertModel`],[`wav2vec2`,`Wav2Vec2Model`],[`wav2vec2-bert`,`Wav2Vec2BertModel`],[`unispeech`,`UniSpeechModel`],[`unispeech-sat`,`UniSpeechSatModel`],[`hubert`,`HubertModel`],[`wavlm`,`WavLMModel`],[`audio-spectrogram-transformer`,`ASTModel`],[`vits`,`VitsModel`],[`pyannote`,`PyAnnoteModel`],[`wespeaker-resnet`,`WeSpeakerResNetModel`],[`detr`,`DetrModel`],[`rt_detr`,`RTDetrModel`],[`rt_detr_v2`,`RTDetrV2Model`],[`rf_detr`,`RFDetrModel`],[`d_fine`,`DFineModel`],[`table-transformer`,`TableTransformerModel`],[`vit`,`ViTModel`],[`ijepa`,`IJepaModel`],[`pvt`,`PvtModel`],[`vit_msn`,`ViTMSNModel`],[`vit_mae`,`ViTMAEModel`],[`groupvit`,`GroupViTModel`],[`fastvit`,`FastViTModel`],[`mobilevit`,`MobileViTModel`],[`mobilevitv2`,`MobileViTV2Model`],[`owlvit`,`OwlViTModel`],[`owlv2`,`Owlv2Model`],[`beit`,`BeitModel`],[`deit`,`DeiTModel`],[`hiera`,`HieraModel`],[`convnext`,`ConvNextModel`],[`convnextv2`,`ConvNextV2Model`],[`dinov2`,`Dinov2Model`],[`dinov2_with_registers`,`Dinov2WithRegistersModel`],[`dinov3_vit`,`DINOv3ViTModel`],[`dinov3_convnext`,`DINOv3ConvNextModel`],[`resnet`,`ResNetModel`],[`swin`,`SwinModel`],[`swin2sr`,`Swin2SRModel`],[`donut-swin`,`DonutSwinModel`],[`yolos`,`YolosModel`],[`dpt`,`DPTModel`],[`glpn`,`GLPNModel`],[`hifigan`,`SpeechT5HifiGan`],[`efficientnet`,`EfficientNetModel`],[`decision_transformer`,`DecisionTransformerModel`],[`patchtst`,`PatchTSTModel`],[`patchtsmixer`,`PatchTSMixerModel`],[`mobilenet_v1`,`MobileNetV1Model`],[`mobilenet_v2`,`MobileNetV2Model`],[`mobilenet_v3`,`MobileNetV3Model`],[`mobilenet_v4`,`MobileNetV4Model`],[`maskformer`,`MaskFormerModel`],[`mgp-str`,`MgpstrForSceneTextRecognition`],[`style_text_to_speech_2`,`StyleTextToSpeech2Model`]]),aO=new Map([[`t5`,`T5Model`],[`longt5`,`LongT5Model`],[`mt5`,`MT5Model`],[`bart`,`BartModel`],[`mbart`,`MBartModel`],[`marian`,`MarianModel`],[`whisper`,`WhisperModel`],[`cohere_asr`,`CohereAsrModel`],[`m2m_100`,`M2M100Model`],[`blenderbot`,`BlenderbotModel`],[`blenderbot-small`,`BlenderbotSmallModel`]]),oO=new Map([[`mimi`,`MimiModel`],[`dac`,`DacModel`],[`snac`,`SnacModel`]]),sO=new Map([[`bloom`,`BloomModel`],[`jais`,`JAISModel`],[`gpt2`,`GPT2Model`],[`gpt_oss`,`GptOssModel`],[`gptj`,`GPTJModel`],[`gpt_bigcode`,`GPTBigCodeModel`],[`gpt_neo`,`GPTNeoModel`],[`gpt_neox`,`GPTNeoXModel`],[`codegen`,`CodeGenModel`],[`llama`,`LlamaModel`],[`apertus`,`ApertusModel`],[`nanochat`,`NanoChatModel`],[`arcee`,`ArceeModel`],[`afmoe`,`AfmoeModel`],[`lfm2`,`Lfm2Model`],[`lfm2_moe`,`Lfm2MoeModel`],[`smollm3`,`SmolLM3Model`],[`exaone`,`ExaoneModel`],[`olmo`,`OlmoModel`],[`olmo2`,`Olmo2Model`],[`olmo3`,`Olmo3Model`],[`olmo_hybrid`,`OlmoHybridModel`],[`mobilellm`,`MobileLLMModel`],[`granite`,`GraniteModel`],[`granitemoehybrid`,`GraniteMoeHybridModel`],[`cohere`,`CohereModel`],[`cohere2`,`Cohere2Model`],[`gemma`,`GemmaModel`],[`gemma2`,`Gemma2Model`],[`vaultgemma`,`VaultGemmaModel`],[`gemma3_text`,`Gemma3Model`],[`helium`,`HeliumModel`],[`glm`,`GlmModel`],[`glm_moe_dsa`,`GlmMoeDsaModel`],[`openelm`,`OpenELMModel`],[`qwen2`,`Qwen2Model`],[`qwen2_moe`,`Qwen2MoeModel`],[`qwen3`,`Qwen3Model`],[`qwen3_moe`,`Qwen3MoeModel`],[`qwen3_next`,`Qwen3NextModel`],[`phi`,`PhiModel`],[`phi3`,`Phi3Model`],[`mpt`,`MptModel`],[`opt`,`OPTModel`],[`mistral`,`MistralModel`],[`mistral4`,`Mistral4Model`],[`ministral`,`MinistralModel`],[`ministral3`,`Ministral3Model`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2Model`],[`deepseek_v3`,`DeepseekV3Model`],[`falcon`,`FalconModel`],[`falcon_h1`,`FalconH1Model`],[`nemotron_h`,`NemotronHModel`],[`solar_open`,`SolarOpenModel`],[`stablelm`,`StableLmModel`],[`modernbert-decoder`,`ModernBertDecoderModel`],[`hunyuan_v1_dense`,`HunYuanDenseV1Model`],[`youtu`,`YoutuModel`]]),cO=new Map([[`speecht5`,`SpeechT5ForSpeechToText`],[`whisper`,`WhisperForConditionalGeneration`],[`lite-whisper`,`LiteWhisperForConditionalGeneration`],[`moonshine`,`MoonshineForConditionalGeneration`],[`cohere_asr`,`CohereAsrForConditionalGeneration`]]),lO=new Map([[`speecht5`,`SpeechT5ForTextToSpeech`]]),uO=new Map([[`vits`,`VitsModel`],[`musicgen`,`MusicgenForConditionalGeneration`],[`supertonic`,`SupertonicForConditionalGeneration`]]),dO=new Map([[`bert`,`BertForSequenceClassification`],[`eurobert`,`EuroBertForSequenceClassification`],[`neobert`,`NeoBertForSequenceClassification`],[`modernbert`,`ModernBertForSequenceClassification`],[`roformer`,`RoFormerForSequenceClassification`],[`electra`,`ElectraForSequenceClassification`],[`esm`,`EsmForSequenceClassification`],[`convbert`,`ConvBertForSequenceClassification`],[`camembert`,`CamembertForSequenceClassification`],[`deberta`,`DebertaForSequenceClassification`],[`deberta-v2`,`DebertaV2ForSequenceClassification`],[`mpnet`,`MPNetForSequenceClassification`],[`albert`,`AlbertForSequenceClassification`],[`distilbert`,`DistilBertForSequenceClassification`],[`roberta`,`RobertaForSequenceClassification`],[`xlm`,`XLMForSequenceClassification`],[`xlm-roberta`,`XLMRobertaForSequenceClassification`],[`bart`,`BartForSequenceClassification`],[`mbart`,`MBartForSequenceClassification`],[`mobilebert`,`MobileBertForSequenceClassification`],[`squeezebert`,`SqueezeBertForSequenceClassification`]]),fO=new Map([[`bert`,`BertForTokenClassification`],[`eurobert`,`EuroBertForTokenClassification`],[`neobert`,`NeoBertForTokenClassification`],[`modernbert`,`ModernBertForTokenClassification`],[`roformer`,`RoFormerForTokenClassification`],[`electra`,`ElectraForTokenClassification`],[`esm`,`EsmForTokenClassification`],[`convbert`,`ConvBertForTokenClassification`],[`camembert`,`CamembertForTokenClassification`],[`deberta`,`DebertaForTokenClassification`],[`deberta-v2`,`DebertaV2ForTokenClassification`],[`mpnet`,`MPNetForTokenClassification`],[`distilbert`,`DistilBertForTokenClassification`],[`roberta`,`RobertaForTokenClassification`],[`xlm`,`XLMForTokenClassification`],[`xlm-roberta`,`XLMRobertaForTokenClassification`]]),pO=new Map([[`t5`,`T5ForConditionalGeneration`],[`longt5`,`LongT5ForConditionalGeneration`],[`mt5`,`MT5ForConditionalGeneration`],[`bart`,`BartForConditionalGeneration`],[`mbart`,`MBartForConditionalGeneration`],[`marian`,`MarianMTModel`],[`m2m_100`,`M2M100ForConditionalGeneration`],[`blenderbot`,`BlenderbotForConditionalGeneration`],[`blenderbot-small`,`BlenderbotSmallForConditionalGeneration`]]),mO=new Map([[`bloom`,`BloomForCausalLM`],[`gpt2`,`GPT2LMHeadModel`],[`gpt_oss`,`GptOssForCausalLM`],[`jais`,`JAISLMHeadModel`],[`gptj`,`GPTJForCausalLM`],[`gpt_bigcode`,`GPTBigCodeForCausalLM`],[`gpt_neo`,`GPTNeoForCausalLM`],[`gpt_neox`,`GPTNeoXForCausalLM`],[`codegen`,`CodeGenForCausalLM`],[`llama`,`LlamaForCausalLM`],[`nanochat`,`NanoChatForCausalLM`],[`apertus`,`ApertusForCausalLM`],[`llama4_text`,`Llama4ForCausalLM`],[`arcee`,`ArceeForCausalLM`],[`afmoe`,`AfmoeForCausalLM`],[`lfm2`,`Lfm2ForCausalLM`],[`lfm2_moe`,`Lfm2MoeForCausalLM`],[`smollm3`,`SmolLM3ForCausalLM`],[`exaone`,`ExaoneForCausalLM`],[`olmo`,`OlmoForCausalLM`],[`olmo2`,`Olmo2ForCausalLM`],[`olmo3`,`Olmo3ForCausalLM`],[`olmo_hybrid`,`OlmoHybridForCausalLM`],[`mobilellm`,`MobileLLMForCausalLM`],[`granite`,`GraniteForCausalLM`],[`granitemoehybrid`,`GraniteMoeHybridForCausalLM`],[`cohere`,`CohereForCausalLM`],[`cohere2`,`Cohere2ForCausalLM`],[`gemma`,`GemmaForCausalLM`],[`gemma2`,`Gemma2ForCausalLM`],[`vaultgemma`,`VaultGemmaForCausalLM`],[`gemma3_text`,`Gemma3ForCausalLM`],[`gemma3`,`Gemma3ForCausalLM`],[`helium`,`HeliumForCausalLM`],[`glm`,`GlmForCausalLM`],[`glm_moe_dsa`,`GlmMoeDsaForCausalLM`],[`openelm`,`OpenELMForCausalLM`],[`qwen2`,`Qwen2ForCausalLM`],[`qwen2_moe`,`Qwen2MoeForCausalLM`],[`qwen3`,`Qwen3ForCausalLM`],[`qwen3_moe`,`Qwen3MoeForCausalLM`],[`qwen3_next`,`Qwen3NextForCausalLM`],[`qwen2_vl`,`Qwen2VLForCausalLM`],[`qwen2_5_vl`,`Qwen2_5_VLForCausalLM`],[`qwen3_vl`,`Qwen3VLForCausalLM`],[`qwen3_vl_moe`,`Qwen3VLMoeForCausalLM`],[`qwen3_5`,`Qwen3_5ForCausalLM`],[`qwen3_5_text`,`Qwen3_5ForCausalLM`],[`qwen3_5_moe`,`Qwen3_5MoeForCausalLM`],[`gemma3n`,`Gemma3nForCausalLM`],[`gemma4`,`Gemma4ForCausalLM`],[`phi`,`PhiForCausalLM`],[`phi3`,`Phi3ForCausalLM`],[`mpt`,`MptForCausalLM`],[`opt`,`OPTForCausalLM`],[`mbart`,`MBartForCausalLM`],[`mistral`,`MistralForCausalLM`],[`mistral4`,`Mistral4ForCausalLM`],[`ministral`,`MinistralForCausalLM`],[`ministral3`,`Ministral3ForCausalLM`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2ForCausalLM`],[`deepseek_v3`,`DeepseekV3ForCausalLM`],[`falcon`,`FalconForCausalLM`],[`falcon_h1`,`FalconH1ForCausalLM`],[`nemotron_h`,`NemotronHForCausalLM`],[`trocr`,`TrOCRForCausalLM`],[`solar_open`,`SolarOpenForCausalLM`],[`stablelm`,`StableLmForCausalLM`],[`modernbert-decoder`,`ModernBertDecoderForCausalLM`],[`hunyuan_v1_dense`,`HunYuanDenseV1ForCausalLM`],[`youtu`,`YoutuForCausalLM`],[`phi3_v`,`Phi3VForCausalLM`]]),hO=new Map([[`multi_modality`,`MultiModalityCausalLM`]]),gO=new Map([[`bert`,`BertForMaskedLM`],[`eurobert`,`EuroBertForMaskedLM`],[`neobert`,`NeoBertForMaskedLM`],[`modernbert`,`ModernBertForMaskedLM`],[`roformer`,`RoFormerForMaskedLM`],[`electra`,`ElectraForMaskedLM`],[`esm`,`EsmForMaskedLM`],[`convbert`,`ConvBertForMaskedLM`],[`camembert`,`CamembertForMaskedLM`],[`deberta`,`DebertaForMaskedLM`],[`deberta-v2`,`DebertaV2ForMaskedLM`],[`mpnet`,`MPNetForMaskedLM`],[`albert`,`AlbertForMaskedLM`],[`distilbert`,`DistilBertForMaskedLM`],[`roberta`,`RobertaForMaskedLM`],[`xlm`,`XLMWithLMHeadModel`],[`xlm-roberta`,`XLMRobertaForMaskedLM`],[`mobilebert`,`MobileBertForMaskedLM`],[`squeezebert`,`SqueezeBertForMaskedLM`]]),_O=new Map([[`bert`,`BertForQuestionAnswering`],[`neobert`,`NeoBertForQuestionAnswering`],[`roformer`,`RoFormerForQuestionAnswering`],[`electra`,`ElectraForQuestionAnswering`],[`convbert`,`ConvBertForQuestionAnswering`],[`camembert`,`CamembertForQuestionAnswering`],[`deberta`,`DebertaForQuestionAnswering`],[`deberta-v2`,`DebertaV2ForQuestionAnswering`],[`mpnet`,`MPNetForQuestionAnswering`],[`albert`,`AlbertForQuestionAnswering`],[`distilbert`,`DistilBertForQuestionAnswering`],[`roberta`,`RobertaForQuestionAnswering`],[`xlm`,`XLMForQuestionAnswering`],[`xlm-roberta`,`XLMRobertaForQuestionAnswering`],[`mobilebert`,`MobileBertForQuestionAnswering`],[`squeezebert`,`SqueezeBertForQuestionAnswering`]]),vO=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`]]),yO=new Map([[`llava`,`LlavaForConditionalGeneration`],[`llava_onevision`,`LlavaOnevisionForConditionalGeneration`],[`moondream1`,`Moondream1ForConditionalGeneration`],[`florence2`,`Florence2ForConditionalGeneration`],[`qwen2_vl`,`Qwen2VLForConditionalGeneration`],[`qwen2_5_vl`,`Qwen2_5_VLForConditionalGeneration`],[`qwen3_vl`,`Qwen3VLForConditionalGeneration`],[`qwen3_vl_moe`,`Qwen3VLMoeForConditionalGeneration`],[`qwen3_5`,`Qwen3_5ForConditionalGeneration`],[`qwen3_5_moe`,`Qwen3_5MoeForConditionalGeneration`],[`lfm2_vl`,`Lfm2VlForConditionalGeneration`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`],[`paligemma`,`PaliGemmaForConditionalGeneration`],[`llava_qwen2`,`LlavaQwen2ForCausalLM`],[`gemma3`,`Gemma3ForConditionalGeneration`],[`gemma3n`,`Gemma3nForConditionalGeneration`],[`gemma4`,`Gemma4ForConditionalGeneration`],[`mistral3`,`Mistral3ForConditionalGeneration`],[`lighton_ocr`,`LightOnOcrForConditionalGeneration`],[`glm_ocr`,`GlmOcrForConditionalGeneration`]]),bO=new Map([[`granite_speech`,`GraniteSpeechForConditionalGeneration`],[`ultravox`,`UltravoxModel`],[`voxtral`,`VoxtralForConditionalGeneration`],[`voxtral_realtime`,`VoxtralRealtimeForConditionalGeneration`]]),xO=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`]]),SO=new Map([[`vit`,`ViTForImageClassification`],[`ijepa`,`IJepaForImageClassification`],[`pvt`,`PvtForImageClassification`],[`vit_msn`,`ViTMSNForImageClassification`],[`fastvit`,`FastViTForImageClassification`],[`mobilevit`,`MobileViTForImageClassification`],[`mobilevitv2`,`MobileViTV2ForImageClassification`],[`beit`,`BeitForImageClassification`],[`deit`,`DeiTForImageClassification`],[`hiera`,`HieraForImageClassification`],[`convnext`,`ConvNextForImageClassification`],[`convnextv2`,`ConvNextV2ForImageClassification`],[`dinov2`,`Dinov2ForImageClassification`],[`dinov2_with_registers`,`Dinov2WithRegistersForImageClassification`],[`resnet`,`ResNetForImageClassification`],[`swin`,`SwinForImageClassification`],[`segformer`,`SegformerForImageClassification`],[`efficientnet`,`EfficientNetForImageClassification`],[`mobilenet_v1`,`MobileNetV1ForImageClassification`],[`mobilenet_v2`,`MobileNetV2ForImageClassification`],[`mobilenet_v3`,`MobileNetV3ForImageClassification`],[`mobilenet_v4`,`MobileNetV4ForImageClassification`]]),CO=new Map([[`detr`,`DetrForObjectDetection`],[`rt_detr`,`RTDetrForObjectDetection`],[`rt_detr_v2`,`RTDetrV2ForObjectDetection`],[`rf_detr`,`RFDetrForObjectDetection`],[`d_fine`,`DFineForObjectDetection`],[`table-transformer`,`TableTransformerForObjectDetection`],[`yolos`,`YolosForObjectDetection`]]),wO=new Map([[`owlvit`,`OwlViTForObjectDetection`],[`owlv2`,`Owlv2ForObjectDetection`],[`grounding-dino`,`GroundingDinoForObjectDetection`]]),TO=new Map([[`detr`,`DetrForSegmentation`],[`clipseg`,`CLIPSegForImageSegmentation`]]),EO=new Map([[`segformer`,`SegformerForSemanticSegmentation`],[`sapiens`,`SapiensForSemanticSegmentation`],[`swin`,`SwinForSemanticSegmentation`],[`mobilenet_v1`,`MobileNetV1ForSemanticSegmentation`],[`mobilenet_v2`,`MobileNetV2ForSemanticSegmentation`],[`mobilenet_v3`,`MobileNetV3ForSemanticSegmentation`],[`mobilenet_v4`,`MobileNetV4ForSemanticSegmentation`]]),DO=new Map([[`detr`,`DetrForSegmentation`],[`maskformer`,`MaskFormerForInstanceSegmentation`]]),OO=new Map([[`sam`,`SamModel`],[`sam2`,`Sam2Model`],[`edgetam`,`EdgeTamModel`],[`sam3_tracker`,`Sam3TrackerModel`]]),kO=new Map([[`wav2vec2`,`Wav2Vec2ForCTC`],[`wav2vec2-bert`,`Wav2Vec2BertForCTC`],[`unispeech`,`UniSpeechForCTC`],[`unispeech-sat`,`UniSpeechSatForCTC`],[`wavlm`,`WavLMForCTC`],[`hubert`,`HubertForCTC`],[`parakeet_ctc`,`ParakeetForCTC`]]),AO=new Map([[`wav2vec2`,`Wav2Vec2ForSequenceClassification`],[`wav2vec2-bert`,`Wav2Vec2BertForSequenceClassification`],[`unispeech`,`UniSpeechForSequenceClassification`],[`unispeech-sat`,`UniSpeechSatForSequenceClassification`],[`wavlm`,`WavLMForSequenceClassification`],[`hubert`,`HubertForSequenceClassification`],[`audio-spectrogram-transformer`,`ASTForAudioClassification`]]),jO=new Map([[`wavlm`,`WavLMForXVector`]]),MO=new Map([[`unispeech-sat`,`UniSpeechSatForAudioFrameClassification`],[`wavlm`,`WavLMForAudioFrameClassification`],[`wav2vec2`,`Wav2Vec2ForAudioFrameClassification`],[`pyannote`,`PyAnnoteForAudioFrameClassification`]]),NO=new Map([[`vitmatte`,`VitMatteForImageMatting`]]),PO=new Map([[`patchtst`,`PatchTSTForPrediction`],[`patchtsmixer`,`PatchTSMixerForPrediction`]]),FO=new Map([[`swin2sr`,`Swin2SRForImageSuperResolution`]]),IO=new Map([[`chmv2`,`CHMv2ForDepthEstimation`],[`dpt`,`DPTForDepthEstimation`],[`depth_anything`,`DepthAnythingForDepthEstimation`],[`glpn`,`GLPNForDepthEstimation`],[`sapiens`,`SapiensForDepthEstimation`],[`depth_pro`,`DepthProForDepthEstimation`],[`metric3d`,`Metric3DForDepthEstimation`],[`metric3dv2`,`Metric3Dv2ForDepthEstimation`]]),LO=new Map([[`sapiens`,`SapiensForNormalEstimation`]]),RO=new Map([[`vitpose`,`VitPoseForPoseEstimation`]]),zO=new Map([[`clip`,`CLIPVisionModelWithProjection`],[`siglip`,`SiglipVisionModel`],[`jina_clip`,`JinaCLIPVisionModel`]]),BO=[[iO,Y.EncoderOnly],[aO,Y.EncoderDecoder],[sO,Y.DecoderOnlyWithoutHead],[oO,Y.AutoEncoder],[dO,Y.EncoderOnly],[fO,Y.EncoderOnly],[pO,Y.Seq2Seq],[cO,Y.Seq2Seq],[mO,Y.DecoderOnly],[hO,Y.MultiModality],[gO,Y.EncoderOnly],[_O,Y.EncoderOnly],[vO,Y.Vision2Seq],[yO,Y.ImageTextToText],[bO,Y.AudioTextToText],[SO,Y.EncoderOnly],[TO,Y.EncoderOnly],[DO,Y.EncoderOnly],[EO,Y.EncoderOnly],[NO,Y.EncoderOnly],[PO,Y.EncoderOnly],[FO,Y.EncoderOnly],[IO,Y.EncoderOnly],[LO,Y.EncoderOnly],[RO,Y.EncoderOnly],[CO,Y.EncoderOnly],[wO,Y.EncoderOnly],[OO,Y.MaskGeneration],[kO,Y.EncoderOnly],[AO,Y.EncoderOnly],[lO,Y.Seq2Seq],[uO,Y.EncoderOnly],[jO,Y.EncoderOnly],[MO,Y.EncoderOnly],[zO,Y.EncoderOnly]];for(let[e,t]of BO)for(let n of e.values()){Vh.set(n,t);let e=lg[n];Uh.set(e,n),Hh.set(n,e)}var VO=[[`MusicgenForConditionalGeneration`,CC,Y.Musicgen],[`Phi3VForCausalLM`,ww,Y.Phi3V],[`CLIPTextModelWithProjection`,g_,Y.EncoderOnly],[`SiglipTextModel`,VT,Y.EncoderOnly],[`JinaCLIPTextModel`,Sx,Y.EncoderOnly],[`ClapTextModelWithProjection`,d_,Y.EncoderOnly],[`ClapAudioModelWithProjection`,f_,Y.EncoderOnly],[`DacEncoderModel`,rv,Y.EncoderOnly],[`DacDecoderModel`,iv,Y.EncoderOnly],[`MimiEncoderModel`,dS,Y.EncoderOnly],[`MimiDecoderModel`,fS,Y.EncoderOnly],[`SnacEncoderModel`,YT,Y.EncoderOnly],[`SnacDecoderModel`,XT,Y.EncoderOnly],[`Gemma3nForConditionalGeneration`,$y,Y.ImageAudioTextToText],[`Gemma4ForConditionalGeneration`,tb,Y.ImageAudioTextToText],[`SupertonicForConditionalGeneration`,yE,Y.Supertonic],[`ChatterboxModel`,i_,Y.Chatterbox],[`VoxtralRealtimeForConditionalGeneration`,bD,Y.VoxtralRealtime]];for(let[e,t,n]of VO)Vh.set(e,n),Uh.set(t,e),Hh.set(e,t);var HO=new Map([[`modnet`,TO],[`birefnet`,TO],[`isnet`,TO],[`ben`,TO]]);for(let[e,t]of HO.entries())t.set(e,`PreTrainedModel`),Vh.set(e,Y.EncoderOnly),Hh.set(e,X);var UO=new Set(HO.keys());Vh.set(`PreTrainedModel`,Y.EncoderOnly),Uh.set(X,`PreTrainedModel`);var WO={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:dO,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:fO,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:lO,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:uO,MODEL_FOR_MASKED_LM_MAPPING_NAMES:gO,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:_O,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:SO,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:TO,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:EO,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:DO,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:CO,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:wO,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:OO,MODEL_FOR_CTC_MAPPING_NAMES:kO,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:AO,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:jO,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:MO,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:xO,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:NO,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:FO,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:IO,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:LO,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:RO,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:zO,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:yO,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:bO,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:pO,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:cO,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:mO,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:vO};Ih(WO);var GO=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d};if(f.config=await Hm.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:p}=f.config;for(let t of this.MODEL_CLASS_MAPPINGS){let n=t.get(p);if(!n){for(let e of t.values())if(e[0]===p){n=e;break}if(!n)continue}return await lg[n].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return UO.has(p)||V.warn(`Unknown model class "${p}", attempting to construct from base class.`),await X.from_pretrained(e,f);throw Error(`Unsupported model type: ${p}`)}},KO=class extends GO{static MODEL_CLASS_MAPPINGS=BO.map(e=>e[0]);static BASE_IF_FAIL=!0},qO=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},JO=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},YO=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},XO=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},ZO=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},QO=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},$O=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},ek=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},tk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},nk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},rk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},ik=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},ak=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},ok=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},sk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},ck=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var lk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_CTC_MAPPING_NAMES]},uk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var dk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var fk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},pk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var mk=class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]}),class extends GO{static MODEL_CLASS_MAPPINGS=[WO.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function hk(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>nf.read(e)))}async function gk(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?od(e,t):e instanceof Float64Array?new Float32Array(e):e))}function _k(e,t){t&&(e=e.map(e=>e|0));let[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}var vk=class extends li{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}},yk=class extends vk{async _call(e,{top_k:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),{problem_type:i,id2label:a}=this.model.config,o=i===`multi_label_classification`?e=>e.sigmoid():e=>new q(`float32`,_c(e.data),e.dims),s=[];for(let e of r.logits){let n=await gl(o(e),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));t===1?s.push(...i):s.push(i)}return Array.isArray(e)||t===1?s:s[0]}},bk=class extends vk{async _call(e,{ignore_labels:t=[`O`]}={}){let n=Array.isArray(e),r=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(r)).logits,a=this.model.config.id2label,o=[];for(let e=0;ee==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;ne==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=_c(i).map((e,t)=>[e,t]),m=_c(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=gi(p,m).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),g=[];for(let e=0;ee==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await gl(new q(`float32`,_c(l.data),l.dims),t),d=u[0].tolist(),f=u[1].tolist();o.push(f.map((e,t)=>{let n=i.slice();return n[c]=e,{score:d[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Ck=class extends vk{_default_generation_config={max_new_tokens:256};_key=`generated_text`;async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,i={padding:!0,truncation:!0},a;a=this.task===`translation`&&`_build_translation_inputs`in r?r._build_translation_inputs(e,i,t):r(e,i);let o=await this.model.generate({...a,...this._default_generation_config,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},wk=class extends Ck{_key=`summary_text`},Tk=class extends Ck{_key=`translation_text`};function Ek(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var Dk=class extends vk{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let n=!1,r=!1,i=t.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=t.tokenizer_encode_kwargs,o;if(typeof e==`string`)o=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))n=!0,o=e;else{if(Ek(e))e=[e];else if(Array.isArray(e)&&e.every(Ek))n=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);r=!0,o=e.map(e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,...a})),i=!1,a=void 0}let s=r?!1:t.return_full_text??!0;this.tokenizer.padding_side=`left`;let c=this.tokenizer(o,{add_special_tokens:i,padding:!0,truncation:!0,...a}),l=await this.model.generate({...c,...this._default_generation_config,...t}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}),d;!s&&c.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(c.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let f=Array.from({length:e.length},e=>[]);for(let t=0;t[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(V.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&&(V.warn(`Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.`),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n=`This example is {}.`,multi_label:r=!1}={}){let i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>n.replace(`{}`,e)),o=r||t.length===1,s=[];for(let n of e){let e=[];for(let t of a){let r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);o?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}let r=(o?e.map(e=>_c(e)[1]):_c(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);s.push({sequence:n,labels:r.map(e=>t[e[1]]),scores:r.map(e=>e[0])})}return i?s:s[0]}},kk=class extends vk{async _call(e,{top_k:t=5}={}){let n=this.processor.feature_extractor.config.sampling_rate,r=await gk(e,n),i=this.model.config.id2label,a=[];for(let e of r){let n=await this.processor(e),r=(await this.model(n)).logits[0],o=await gl(new q(`float32`,_c(r.data),r.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:s[t]}));a.push(c)}return Array.isArray(e)?a:a[0]}},Ak=class extends vk{async _call(e,t,{hypothesis_template:n=`This is a sound of {}.`}={}){let r=!Array.isArray(e);r&&(e=[e]);let i=t.map(e=>n.replace(`{}`,e)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,s=await gk(e,o),c=[];for(let e of s){let n=await this.processor(e),r=_c((await this.model({...a,...n})).logits_per_audio.data);c.push([...r].map((e,n)=>({score:e,label:t[n]})))}return r?c[0]:c}},jk=class extends vk{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);case`cohere_asr`:return this._call_cohere_asr(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&V.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&V.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await gk(r,i),o=[];for(let e of a){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push(bc(e.data)[1]);let i=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();o.push({text:i})}return n?o[0]:o}async _call_whisper(e,t){let n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};n===`word`&&(o.return_token_timestamps=!0,o.return_timestamps=!0);let s=!Array.isArray(e),c=s?[e]:e,l=this.processor.feature_extractor.config,u=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,f=l.sampling_rate,p=await gk(c,f),m=[];for(let e of p){let t=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let n=f*r,i=f*a,o=n-2*i,s=0;for(;;){let r=s+n,a=e.subarray(s,r),c=await this.processor(a),l=s===0,u=r>=e.length;if(t.push({stride:[a.length,l?0:i,u?0:i],input_features:c.input_features,is_last:u}),u)break;s+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){o.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...o});if(n===`word`){let n=t.sequences.tolist()[0],r=t.token_timestamps.tolist()[0],i=this.tokenizer.timestamp_begin,a=Math.max(n.findIndex(e=>Number(e)>=i),0);e.tokens=n.slice(a),e.token_timestamps=r.slice(a).map(e=>Ec(e,2))}else e.tokens=t[0].tolist();e.stride=e.stride.map(e=>e/f)}let[s,c]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:s,...c})}return s?m[0]:m}async _call_moonshine(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await gk(r,i),o=[];for(let e of a){let n=await this.processor(e),r=Math.floor(e.length/i)*6,a=await this.model.generate({max_new_tokens:r,...t,...n}),s=this.processor.batch_decode(a,{skip_special_tokens:!0})[0];o.push({text:s})}return n?o[0]:o}async _call_cohere_asr(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor,a=i.config.sampling_rate,o=await gk(r,a),s=t.language??`en`,c=this.processor.get_decoder_prompt_ids(s),l=[];for(let e of o){let n=i.split_audio(e),r=[];for(let e of n){let n=await this.processor(e),i=await this.model.generate({...n,decoder_input_ids:c,...t}),a=this.tokenizer.decode(i[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,s);l.push({text:a})}return n?l[0]:l}},Mk=class extends vk{DEFAULT_VOCODER_ID=`Xenova/speecht5_hifigan`;constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e==`string`||e instanceof URL)&&(e=new Float32Array(await(await si.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new q(`float32`,e,[e.length]);else if(!(e instanceof q))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,n,r=null){let i=t.data,[a,o]=t.dims,s=r?r.data:null,c=[];for(let e=0;e({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},Pk=class extends vk{async _call(e,{top_k:t=5}={}){let n=await hk(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(let e of i.logits){let n=await gl(new q(`float32`,_c(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));o.push(i)}return Array.isArray(e)?o:o[0]}},Fk={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},Ik=class extends vk{async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error(`Image segmentation pipeline currently only supports a batch size of 1.`);let s=await hk(e),c=s.map(e=>[e.height,e.width]),l=await this.processor(s),{inputNames:u,outputNames:d}=this.model.sessions.model;if(!u.includes(`pixel_values`)){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);let e=u[0];if(e in l)throw Error(`Input name ${e} already exists in the inputs.`);l[e]=l.pixel_values}let f=await this.model(l),p=null;if(o!==null)p=Fk[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(Fk))if(t in this.processor.image_processor){p=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}}let m=this.model.config.id2label,h=[];if(!o){let e=1e-5,t=f[d[0]];for(let n=0;nt<-e||t>1+e)&&i.sigmoid_();let a=await nf.fromTensor(i.mul_(255).to(`uint8`)).resize(r[1],r[0]);h.push({label:null,score:null,mask:a})}}else if(o===`panoptic`||o===`instance`){let e=p(f,t,n,r,i,a??c)[0],o=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let n=0;n{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},model:[ik,ak,ok],default:{model:`Xenova/modnet`},type:`image`},"zero-shot-image-classification":{pipeline:class extends vk{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await hk(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type===`siglip`?`max_length`:!0,truncation:!0}),{pixel_values:s}=await this.processor(i),c=await this.model({...o,pixel_values:s}),l=this.model.config.model_type===`siglip`?e=>e.sigmoid().data:e=>_c(e.data),u=[];for(let e of c.logits_per_image){let n=[...l(e)].map((e,n)=>({score:e,label:t[n]}));n.sort((e,t)=>t.score-e.score),u.push(n)}return r?u:u[0]}},model:KO,default:{model:`Xenova/clip-vit-base-patch32`},type:`multimodal`},"object-detection":{pipeline:class extends vk{async _call(e,{threshold:t=.9,percentage:n=!1}={}){let r=Array.isArray(e);if(r&&e.length!==1)throw Error(`Object detection pipeline currently only supports a batch size of 1.`);let i=await hk(e),a=n?null:i.map(e=>[e.height,e.width]),{pixel_values:o,pixel_mask:s}=await this.processor(i),c=await this.model({pixel_values:o,pixel_mask:s}),l=this.processor.image_processor.post_process_object_detection(c,t,a),{id2label:u}=this.model.config,d=l.map(e=>e.boxes.map((t,r)=>({score:e.scores[r],label:u[e.classes[r]],box:_k(t,!n)})));return r?d:d[0]}},model:sk,default:{model:`Xenova/detr-resnet-50`},type:`multimodal`},"zero-shot-object-detection":{pipeline:class extends vk{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await hk(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e({score:e.scores[n],label:e.labels[n],box:_k(t,!i)}))}else{let e=this.processor.image_processor.post_process_object_detection(f,n,u,!0)[0];p=e.boxes.map((n,r)=>({score:e.scores[r],label:t[e.classes[r]],box:_k(n,!i)}))}p.sort((e,t)=>t.score-e.score),r!==null&&(p=p.slice(0,r)),l.push(p)}return a?l:l[0]}},model:ck,default:{model:`Xenova/owlvit-base-patch32`},type:`multimodal`},"document-question-answering":{pipeline:class extends vk{_default_generation_config={max_new_tokens:256};async _call(e,t,n={}){if(Array.isArray(e)){if(e.length!==1)throw Error(`Document Question Answering pipeline currently only supports a batch size of 1.`);e=e[0]}let r=(await hk(e))[0],{pixel_values:i}=await this.processor(r),a=`${t}`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,s=await this.model.generate({inputs:i,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...n}),c=this.tokenizer.batch_decode(s)[0].match(/(.*?)<\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},model:dk,default:{model:`Xenova/donut-base-finetuned-docvqa`},type:`multimodal`},"image-to-image":{pipeline:class extends vk{async _call(e){let t=await hk(e),n=await this.processor(t),r=await this.model(n),i=[];for(let e of r.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to(`uint8`);i.push(nf.fromTensor(t))}return Array.isArray(e)?i:i[0]}},model:fk,default:{model:`Xenova/swin2SR-classical-sr-x2-64`},type:`image`},"depth-estimation":{pipeline:class extends vk{async _call(e){let t=await hk(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;ee>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,Rk=class{put(e){throw Error(`Not implemented`)}end(){throw Error(`Not implemented`)}},zk=Qr.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),Bk=class extends Rk{constructor(e,{skip_prompt:t=!1,callback_function:n=null,token_callback_function:r=null,skip_special_tokens:i=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=n??zk,this.token_callback_function=r,this.decode_kwargs={skip_special_tokens:i,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error(`TextStreamer only supports batch size of 1`);let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let n=e[0];if(this.token_callback_function?.(n),n.length===1&&this.special_ids.has(n[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(e,!1),this.token_cache=[],this.print_len=0}let e=this.tokenizer.decode(n,this.decode_kwargs);this.on_finalized_text(e,!1);return}this.token_cache=hi(this.token_cache,n);let r=this.tokenizer.decode(this.token_cache,this.decode_kwargs),i;t||r.endsWith(` +`)?(i=r.slice(this.print_len),this.token_cache=[],this.print_len=0):r.length>0&&Lk(r.charCodeAt(r.length-1))?(i=r.slice(this.print_len),this.print_len+=i.length):(i=r.slice(this.print_len,r.lastIndexOf(` `)+1),this.print_len+=i.length),this.on_finalized_text(i,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e=``,this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===zk&&Qr.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}},Vk=(0,f.createContext)(null);function Hk(e){let t=e.replace(/```json\s*/g,``).replace(/```\s*/g,``).trim();try{let e=JSON.parse(t);if(Array.isArray(e))return Uk(e)}catch{}let n=t.match(/\[[\s\S]*\]/);if(n)try{let e=JSON.parse(n[0]);if(Array.isArray(e))return Uk(e)}catch{}return[]}function Uk(e){return e.filter(e=>typeof e==`object`&&!!e&&`box_2d`in e&&Array.isArray(e.box_2d)&&e.box_2d.length===4)}function Wk(e,t,n){let[r,i,a,o]=e;return[i/1e3*t,r/1e3*n,o/1e3*t,a/1e3*n]}var Gk=[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f9ca24`,`#6c5ce7`,`#a8e6cf`,`#fd79a8`,`#fdcb6e`,`#0984e3`,`#00b894`,`#e17055`,`#74b9ff`],Kk=t((e=>{var t=Symbol.for(`react.transitional.element`);function n(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.jsx=n,e.jsxs=n})),Z=t(((e,t)=>{t.exports=Kk()}))(),qk=`onnx-community/gemma-4-E2B-it-ONNX`;async function Jk(){try{let e=await navigator.gpu?.requestAdapter({powerPreference:`high-performance`});if(e){let t=[...e.features];if(console.log(`[Gemma4] WebGPU adapter features:`,t),console.log(`[Gemma4] WebGPU adapter limits:`,e.limits),e.features.has(`shader-f16`))return console.log(`[Gemma4] shader-f16 is AVAILABLE — using q4f16 (fast)`),`q4f16`;console.log(`[Gemma4] shader-f16 NOT available — falling back to q4 (slow)`)}}catch(e){console.warn(`[Gemma4] Adapter probe failed:`,e)}return`q4`}function Yk({children:e}){let t=(0,f.useRef)(null),n=(0,f.useRef)(null),[r,i]=(0,f.useState)({state:`idle`}),[a,o]=(0,f.useState)(!1),s=(0,f.useRef)(!1),[c,l]=(0,f.useState)(0),[u,d]=(0,f.useState)(null),[p,m]=(0,f.useState)(null),h=(0,f.useRef)(!1);s.current=a;let g=(0,f.useCallback)(()=>{t.current||=(async()=>{i({state:`loading`,message:`Loading processor...`});try{let e=await Jk();d(e),console.log(`[Gemma4] Using dtype: ${e}`),n.current=await Im.from_pretrained(qk),i({state:`loading`,message:`Downloading model...`});let t=await tb.from_pretrained(qk,{dtype:e,device:`webgpu`,progress_callback:e=>{e.status===`progress_total`&&typeof e.progress==`number`&&i({state:`loading`,progress:e.progress,message:`Loading model...`})}});return i({state:`ready`}),t}catch(e){throw console.error(`[Gemma4] Model loading failed:`,e),i({state:`error`,error:e instanceof Error?e.message:String(e)}),t.current=null,e}})()},[]),_=(0,f.useCallback)(async(e,r)=>{if(!t.current){console.warn(`[Gemma4] detect() called before model loaded`);return}if(s.current){console.warn(`[Gemma4] detect() called while already generating`);return}console.log(`[Gemma4] Starting detection...`),o(!0),l(0),m(null),h.current=!1;try{let i=await t.current,a=n.current,o=[{role:`user`,content:[{type:`image`},{type:`text`,text:r}]}],s=await a(a.apply_chat_template(o,{enable_thinking:!1,add_generation_prompt:!0}),await rf(e),null,{add_special_tokens:!1}),c=``,u=0,d=0,f=new Bk(a.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:e=>{if(h.current)return;c+=e;let t=Hk(c);m({text:c,detections:t})},token_callback_function:()=>{if(u++,u===1)d=performance.now();else{let e=(performance.now()-d)/1e3;e>0&&l(Math.round((u-1)/e*10)/10)}}});await i.generate({...s,max_new_tokens:128,do_sample:!0,temperature:1,top_p:.95,top_k:64,streamer:f});let p=Hk(c);m({text:c,detections:p}),console.log(`[Gemma4] Detection done. ${p.length} objects found.`)}catch(e){console.error(`[Gemma4] Detection error:`,e);let t=e instanceof Error?e.message:String(e);m({text:`Error: ${t.includes(`OUT_OF_DEVICE_MEMORY`)||t.includes(`Invalid Buffer`)||t.includes(`Softmax`)?`GPU ran out of memory. Enable chrome://flags/#enable-unsafe-webgpu and chrome://flags/#enable-vulkan, restart Chrome, and close other GPU-heavy tabs.`:t}`,detections:[]})}o(!1)},[]),v=(0,f.useCallback)(()=>{h.current=!0},[]);return(0,Z.jsx)(Vk.Provider,{value:{status:r,isGenerating:a,tps:c,dtype:u,result:p,loadModel:g,detect:_,stop:v},children:e})}var Xk=`181`,Zk=0,Qk=1,$k=2,eA=100,tA=101,nA=102,rA=200,iA=201,aA=202,oA=203,sA=204,cA=205,lA=206,uA=207,dA=208,fA=209,pA=210,mA=211,hA=212,gA=213,_A=214,vA=0,yA=1,bA=2,xA=3,SA=4,CA=5,wA=6,TA=7,EA=301,DA=302,OA=303,kA=306,AA=1e3,jA=1001,MA=1002,NA=1003,PA=1004,FA=1005,IA=1006,LA=1007,RA=1008,zA=1009,BA=1010,VA=1011,HA=1012,UA=1013,WA=1014,GA=1015,KA=1016,qA=1017,JA=1018,YA=1020,XA=35902,ZA=35899,QA=1023,$A=1026,ej=1027,tj=1028,nj=1029,rj=1030,ij=1031,aj=1033,oj=33776,sj=33777,cj=33778,lj=33779,uj=35840,dj=35841,fj=35842,pj=35843,mj=36196,hj=37492,gj=37496,_j=37808,vj=37809,yj=37810,bj=37811,xj=37812,Sj=37813,Cj=37814,wj=37815,Tj=37816,Ej=37817,Dj=37818,Oj=37819,kj=37820,Aj=37821,jj=36492,Mj=36494,Nj=36495,Pj=36283,Fj=36284,Ij=36285,Lj=36286,Rj=``,zj=`srgb`,Bj=`srgb-linear`,Vj=`linear`,Hj=`srgb`,Uj=7680,Wj=512,Gj=513,Kj=514,qj=515,Jj=516,Yj=517,Xj=518,Zj=519,Qj=`300 es`,$j=2e3,eM=2001;function tM(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function nM(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function rM(){let e=nM(`canvas`);return e.style.display=`block`,e}var iM={};function aM(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function oM(...e){let t=`THREE.`+e.shift();console.warn(t,...e)}function sM(...e){let t=`THREE.`+e.shift();console.error(t,...e)}function cM(...e){let t=e.join(` `);t in iM||(iM[t]=!0,oM(...e))}var lM=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n>8&255]+uM[e>>16&255]+uM[e>>24&255]+`-`+uM[255&t]+uM[t>>8&255]+`-`+uM[t>>16&15|64]+uM[t>>24&255]+`-`+uM[63&n|128]+uM[n>>8&255]+`-`+uM[n>>16&255]+uM[n>>24&255]+uM[255&r]+uM[r>>8&255]+uM[r>>16&255]+uM[r>>24&255]).toLowerCase()}function hM(e,t,n){return Math.max(t,Math.min(n,e))}function gM(e,t){return(e%t+t)%t}function _M(e,t,n){return(1-n)*e+n*t}function vM(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function yM(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw Error(`Invalid component type.`)}}var bM={DEG2RAD:fM,RAD2DEG:pM,generateUUID:mM,clamp:hM,euclideanModulo:gM,mapLinear:function(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)},inverseLerp:function(e,t,n){return e===t?0:(n-e)/(t-e)},lerp:_M,damp:function(e,t,n,r){return _M(e,t,1-Math.exp(-n*r))},pingpong:function(e,t=1){return t-Math.abs(gM(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){e!==void 0&&(dM=e);let t=dM+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*fM},radToDeg:function(e){return e*pM},isPowerOfTwo:function(e){return!(e&e-1)&&e!==0},ceilPowerOfTwo:function(e){return 2**Math.ceil(Math.log(e)/Math.LN2)},floorPowerOfTwo:function(e){return 2**Math.floor(Math.log(e)/Math.LN2)},setQuaternionFromProperEuler:function(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:oM(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}},normalize:yM,denormalize:vM},xM=class e{constructor(t=0,n=0){e.prototype.isVector2=!0,this.x=t,this.y=n}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 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 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){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[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=hM(this.x,e.x,t.x),this.y=hM(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=hM(this.x,e,t),this.y=hM(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(hM(n,e,t))}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){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(hM(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,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){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},SM=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(o<=0)return e[t+0]=s,e[t+1]=c,e[t+2]=l,void(e[t+3]=u);if(o>=1)return e[t+0]=d,e[t+1]=f,e[t+2]=p,void(e[t+3]=m);if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,s=s*t+d*(o=Math.sin(o*n)/r),c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,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,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,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){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:oM(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(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=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(hM(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),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*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}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}},Q=class e{constructor(t=0,n=0,r=0){e.prototype.isVector3=!0,this.x=t,this.y=n,this.z=r}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,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 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 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(wM.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(wM.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,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=hM(this.x,e.x,t.x),this.y=hM(this.y,e.y,t.y),this.z=hM(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=hM(this.x,e,t),this.y=hM(this.y,e,t),this.z=hM(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(hM(n,e,t))}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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return CM.copy(this).projectOnVector(e),this.sub(CM)}reflect(e){return this.sub(CM.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(hM(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}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,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}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(){let e=Math.random()*Math.PI*2,t=2*Math.random()-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},CM=new Q,wM=new SM,TM=class e{constructor(t,n,r,i,a,o,s,c,l){e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let 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){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let 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(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,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){let 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,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(EM.makeScale(e,t)),this}rotate(e){return this.premultiply(EM.makeRotation(-e)),this}translate(e,t){return this.premultiply(EM.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){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},EM=new TM,DM=new TM().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),OM=new TM().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function kM(){let e={enabled:!0,workingColorSpace:Bj,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===Hj&&(e.r=jM(e.r),e.g=jM(e.g),e.b=jM(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===Hj&&(e.r=MM(e.r),e.g=MM(e.g),e.b=MM(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===Rj?Vj:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return cM(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return cM(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Bj]:{primaries:t,whitePoint:r,transfer:Vj,toXYZ:DM,fromXYZ:OM,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:zj},outputColorSpaceConfig:{drawingBufferColorSpace:zj}},[zj]:{primaries:t,whitePoint:r,transfer:Hj,toXYZ:DM,fromXYZ:OM,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:zj}}}),e}var AM=kM();function jM(e){return e<.04045?.0773993808*e:(.9478672986*e+.0521327014)**2.4}function MM(e){return e<.0031308?12.92*e:1.055*e**.41666-.055}var NM,PM=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{NM===void 0&&(NM=nM(`canvas`)),NM.width=e.width,NM.height=e.height;let t=NM.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=NM}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=nM(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e1),this.pmremVersion=0}get width(){return this.source.getSize(zM).x}get height(){return this.source.getSize(zM).y}get depth(){return this.source.getSize(zM).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){oM(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];r===void 0?oM(`Texture.setValues(): property '${t}' does not exist.`):r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case AA:e.x-=Math.floor(e.x);break;case jA:e.x=e.x<0?0:1;break;case MA:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case AA:e.y-=Math.floor(e.y);break;case jA:e.y=e.y<0?0:1;break;case MA:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}};BM.DEFAULT_IMAGE=null,BM.DEFAULT_MAPPING=300,BM.DEFAULT_ANISOTROPY=1;var VM=class e{constructor(t=0,n=0,r=0,i=1){e.prototype.isVector4=!0,this.x=t,this.y=n,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,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,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 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 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?1:e.w,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){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let 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,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)s&&e>_?e_?s1);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.textures.length=0;for(let t=0,n=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.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.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,JM),JM.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(nN),rN.subVectors(this.max,nN),XM.subVectors(e.a,nN),ZM.subVectors(e.b,nN),QM.subVectors(e.c,nN),$M.subVectors(ZM,XM),eN.subVectors(QM,ZM),tN.subVectors(XM,QM);let t=[0,-$M.z,$M.y,0,-eN.z,eN.y,0,-tN.z,tN.y,$M.z,0,-$M.x,eN.z,0,-eN.x,tN.z,0,-tN.x,-$M.y,$M.x,0,-eN.y,eN.x,0,-tN.y,tN.x,0];return!!oN(t,XM,ZM,QM,rN)&&(t=[1,0,0,0,1,0,0,0,1],!!oN(t,XM,ZM,QM,rN)&&(iN.crossVectors($M,eN),t=[iN.x,iN.y,iN.z],oN(t,XM,ZM,QM,rN)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,JM).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(JM).length()),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()||(qM[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),qM[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),qM[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),qM[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),qM[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),qM[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),qM[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),qM[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(qM)),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)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},qM=[new Q,new Q,new Q,new Q,new Q,new Q,new Q,new Q],JM=new Q,YM=new KM,XM=new Q,ZM=new Q,QM=new Q,$M=new Q,eN=new Q,tN=new Q,nN=new Q,rN=new Q,iN=new Q,aN=new Q;function oN(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){aN.fromArray(e,a);let o=i.x*Math.abs(aN.x)+i.y*Math.abs(aN.y)+i.z*Math.abs(aN.z),s=t.dot(aN),c=n.dot(aN),l=r.dot(aN);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var sN=new KM,cN=new Q,lN=new Q,uN=class{constructor(e=new Q,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){let n=this.center;t===void 0?sN.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;tthis.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*=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;cN.subVectors(e,this.center);let t=cN.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(cN,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(lN.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(cN.copy(e.center).add(lN)),this.expandByPoint(cN.copy(e.center).sub(lN))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},dN=new Q,fN=new Q,pN=new Q,mN=new Q,hN=new Q,gN=new Q,_N=new Q,vN=class{constructor(e=new Q,t=new Q(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,dN)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=dN.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(dN.copy(this.origin).addScaledVector(this.direction,t),dN.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){fN.copy(e).add(t).multiplyScalar(.5),pN.copy(t).sub(e).normalize(),mN.copy(this.origin).sub(fN);let i=.5*e.distanceTo(t),a=-this.direction.dot(pN),o=mN.dot(this.direction),s=-mN.dot(pN),c=mN.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(fN).addScaledVector(pN,d),f}intersectSphere(e,t){dN.subVectors(e.center,this.origin);let n=dN.dot(this.direction),r=dN.dot(dN)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0?!0:e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r?null:((i>n||isNaN(n))&&(n=i),(a=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r?null:((o>n||n!=n)&&(n=o),(s=0?n:r,t)))}intersectsBox(e){return this.intersectBox(e,dN)!==null}intersectTriangle(e,t,n,r,i){hN.subVectors(t,e),gN.subVectors(n,e),_N.crossVectors(hN,gN);let a,o=this.direction.dot(_N);if(o>0){if(r)return null;a=1}else{if(!(o<0))return null;a=-1,o=-o}mN.subVectors(this.origin,e);let s=a*this.direction.dot(gN.crossVectors(mN,gN));if(s<0)return null;let c=a*this.direction.dot(hN.cross(mN));if(c<0||s+c>o)return null;let l=-a*mN.dot(_N);return l<0?null:this.at(l/o,i)}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)}},yN=class e{constructor(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){e.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,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 e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let 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,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,r=1/bN.setFromMatrixColumn(e,0).length(),i=1/bN.setFromMatrixColumn(e,1).length(),a=1/bN.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}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(SN,e,CN)}lookAt(e,t,n){let r=this.elements;return EN.subVectors(e,t),EN.lengthSq()===0&&(EN.z=1),EN.normalize(),wN.crossVectors(n,EN),wN.lengthSq()===0&&(Math.abs(n.z)===1?EN.x+=1e-4:EN.z+=1e-4,EN.normalize(),wN.crossVectors(n,EN)),wN.normalize(),TN.crossVectors(EN,wN),r[0]=wN.x,r[4]=TN.x,r[8]=EN.x,r[1]=wN.y,r[5]=TN.y,r[9]=EN.y,r[2]=wN.z,r[6]=TN.z,r[10]=EN.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],A=r[6],j=r[10],M=r[14],N=r[3],ee=r[7],te=r[11],P=r[15];return i[0]=a*x+o*T+s*k+c*N,i[4]=a*S+o*E+s*A+c*ee,i[8]=a*C+o*D+s*j+c*te,i[12]=a*w+o*O+s*M+c*P,i[1]=l*x+u*T+d*k+f*N,i[5]=l*S+u*E+d*A+f*ee,i[9]=l*C+u*D+d*j+f*te,i[13]=l*w+u*O+d*M+f*P,i[2]=p*x+m*T+h*k+g*N,i[6]=p*S+m*E+h*A+g*ee,i[10]=p*C+m*D+h*j+g*te,i[14]=p*w+m*O+h*M+g*P,i[3]=_*x+v*T+y*k+b*N,i[7]=_*S+v*E+y*A+b*ee,i[11]=_*C+v*D+y*j+b*te,i[15]=_*w+v*O+y*M+b*P,this}multiplyScalar(e){let 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(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14];return e[3]*(+i*s*u-r*c*u-i*o*d+n*c*d+r*o*f-n*s*f)+e[7]*(+t*s*f-t*c*d+i*a*d-r*a*f+r*c*l-i*s*l)+e[11]*(+t*c*u-t*o*f-i*a*u+n*a*f+i*o*l-n*c*l)+e[15]*(-r*o*l-t*s*u+t*o*d+r*a*u-n*a*d+n*s*l)}transpose(){let e=this.elements,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,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let S=1/x;return e[0]=_*S,e[1]=(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,e[2]=(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,e[3]=(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,e[4]=v*S,e[5]=(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,e[6]=(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,e[7]=(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,e[8]=y*S,e[9]=(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,e[10]=(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,e[11]=(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,e[12]=b*S,e[13]=(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,e[14]=(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,e[15]=(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){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,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements,i=bN.set(r[0],r[1],r[2]).length(),a=bN.set(r[4],r[5],r[6]).length(),o=bN.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],xN.copy(this);let s=1/i,c=1/a,l=1/o;return xN.elements[0]*=s,xN.elements[1]*=s,xN.elements[2]*=s,xN.elements[4]*=c,xN.elements[5]*=c,xN.elements[6]*=c,xN.elements[8]*=l,xN.elements[9]*=l,xN.elements[10]*=l,t.setFromRotationMatrix(xN),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a,o=2e3,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===$j)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else{if(o!==eM)throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);p=-a/(a-i),m=-a*i/(a-i)}return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=2e3,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===$j)p=-2/(a-i),m=-(a+i)/(a-i);else{if(o!==eM)throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);p=-1/(a-i),m=-i/(a-i)}return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},bN=new Q,xN=new yN,SN=new Q(0,0,0),CN=new Q(1,1,1),wN=new Q,TN=new Q,EN=new Q,DN=new yN,ON=new SM,kN=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,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,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,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,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(hM(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-hM(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(hM(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-hM(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(hM(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-hM(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:oM(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return DN.makeRotationFromQuaternion(e),this.setFromRotationMatrix(DN,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ON.setFromEuler(this),this.setFromQuaternion(ON,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}};kN.DEFAULT_ORDER=`XYZ`;var AN=class{constructor(){this.mask=1}set(e){this.mask=1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}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)),!0===t)for(let t=0;t0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){qN.subVectors(r,t),JN.subVectors(n,t),YN.subVectors(e,t);let a=qN.dot(qN),o=qN.dot(JN),s=qN.dot(YN),c=JN.dot(JN),l=JN.dot(YN),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,XN)!==null&&XN.x>=0&&XN.y>=0&&XN.x+XN.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,XN)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,XN.x),s.addScaledVector(a,XN.y),s.addScaledVector(o,XN.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return rP.setScalar(0),iP.setScalar(0),aP.setScalar(0),rP.fromBufferAttribute(e,t),iP.fromBufferAttribute(e,n),aP.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(rP,i.x),a.addScaledVector(iP,i.y),a.addScaledVector(aP,i.z),a}static isFrontFacing(e,t,n,r){return qN.subVectors(n,t),JN.subVectors(e,t),qN.cross(JN).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),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 qN.subVectors(this.c,this.b),JN.subVectors(this.a,this.b),.5*qN.cross(JN).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;ZN.subVectors(r,n),QN.subVectors(i,n),eP.subVectors(e,n);let s=ZN.dot(eP),c=QN.dot(eP);if(s<=0&&c<=0)return t.copy(n);tP.subVectors(e,r);let l=ZN.dot(tP),u=QN.dot(tP);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(ZN,a);nP.subVectors(e,i);let f=ZN.dot(nP),p=QN.dot(nP);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(QN,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return $N.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector($N,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(ZN,a).addScaledVector(QN,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},sP={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},cP={h:0,s:0,l:0},lP={h:0,s:0,l:0};function uP(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}var dP=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=zj){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,AM.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=AM.workingColorSpace){return this.r=e,this.g=t,this.b=n,AM.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=AM.workingColorSpace){if(e=gM(e,1),t=hM(t,0,1),n=hM(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=uP(i,r,e+1/3),this.g=uP(i,r,e),this.b=uP(i,r,e-1/3)}return AM.colorSpaceToWorking(this,r),this}setStyle(e,t=zj){function n(t){t!==void 0&&parseFloat(t)<1&&oM(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:oM(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);oM(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=zj){let n=sP[e.toLowerCase()];return n===void 0?oM(`Color: Unknown color `+e):this.setHex(n,t),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=jM(e.r),this.g=jM(e.g),this.b=jM(e.b),this}copyLinearToSRGB(e){return this.r=MM(e.r),this.g=MM(e.g),this.b=MM(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=zj){return AM.workingToColorSpace(fP.copy(this),e),65536*Math.round(hM(255*fP.r,0,255))+256*Math.round(hM(255*fP.g,0,255))+Math.round(hM(255*fP.b,0,255))}getHexString(e=zj){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=AM.workingColorSpace){AM.workingToColorSpace(fP.copy(this),t);let n=fP.r,r=fP.g,i=fP.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){oM(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];r===void 0?oM(`Material: '${t}' is not a property of THREE.${this.type}.`):r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==eA&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Uj&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Uj&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Uj&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}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;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,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){!0===e&&this.version++}},hP=class extends mP{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new dP(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.envMapRotation=new kN,this.combine=0,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.envMapRotation.copy(e.envMapRotation),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}},gP=_P();function _P(){let e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){let t=e-127;t<-27?(r[e]=0,r[256|e]=32768,i[e]=24,i[256|e]=24):t<-14?(r[e]=1024>>-t-14,r[256|e]=1024>>-t-14|32768,i[e]=-t-1,i[256|e]=-t-1):t<=15?(r[e]=t+15<<10,r[256|e]=t+15<<10|32768,i[e]=13,i[256|e]=13):t<128?(r[e]=31744,r[256|e]=64512,i[e]=24,i[256|e]=24):(r[e]=31744,r[256|e]=64512,i[e]=13,i[256|e]=13)}let a=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,a[e]=t|n}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)e!==32&&(s[e]=1024);return{floatView:t,uint32View:n,baseTable:r,shiftTable:i,mantissaTable:a,exponentTable:o,offsetTable:s}}var vP=class{static toHalfFloat(e){return function(e){Math.abs(e)>65504&&oM(`DataUtils.toHalfFloat(): Value out of range.`),e=hM(e,-65504,65504),gP.floatView[0]=e;let t=gP.uint32View[0],n=t>>23&511;return gP.baseTable[n]+((8388607&t)>>gP.shiftTable[n])}(e)}static fromHalfFloat(e){return function(e){let t=e>>10;return gP.uint32View[0]=gP.mantissaTable[gP.offsetTable[t]+(1023&e)]+gP.exponentTable[t],gP.floatView[0]}(e)}},yP=new Q,bP=new xM,xP=0,SP=class{constructor(e,t,n=!1){if(Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,`id`,{value:xP++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=35044,this.updateRanges=[],this.gpuType=GA,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}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,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;rt.count&&oM(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new KM);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return sM(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),void this.boundingBox.set(new Q(-1/0,-1/0,-1/0),new Q(1/0,1/0,1/0));if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),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;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2))return;PP.copy(i).invert(),FP.copy(e.ray).applyMatrix4(PP),n.boundingBox!==null&&!1===FP.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,FP)}}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;in.far?null:{distance:l,point:WP.clone(),object:e}}(e,t,n,r,RP,zP,BP,UP);if(u){let e=new Q;oP.getBarycoord(UP,RP,zP,BP,e),i&&(u.uv=oP.getInterpolatedAttribute(i,s,c,l,e,new xM)),a&&(u.uv1=oP.getInterpolatedAttribute(a,s,c,l,e,new xM)),o&&(u.normal=oP.getInterpolatedAttribute(o,s,c,l,e,new Q),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new Q,materialIndex:0};oP.getNormal(RP,zP,BP,t.normal),u.face=t,u.barycoord=e}return u}var qP=class e extends NP{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new Q;for(let a=0;a0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},$P=class extends KN{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new yN,this.projectionMatrix=new yN,this.projectionMatrixInverse=new yN,this.coordinateSystem=$j,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}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)}},eF=new Q,tF=new xM,nF=new xM,rF=class extends $P{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,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){let t=.5*this.getFilmHeight()/e;this.fov=2*pM*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(.5*fM*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*pM*Math.atan(Math.tan(.5*fM*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){eF.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(eF.x,eF.y).multiplyScalar(-e/eF.z),eF.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(eF.x,eF.y).multiplyScalar(-e/eF.z)}getViewSize(e,t){return this.getViewBounds(e,tF,nF),t.subVectors(nF,tF)}setViewOffset(e,t,n,r,i,a){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=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(.5*fM*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let 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}},iF=-90,aF=class extends KN{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new rF(iF,1,e,t);r.layers=this.layers,this.add(r);let i=new rF(iF,1,e,t);i.layers=this.layers,this.add(i);let a=new rF(iF,1,e,t);a.layers=this.layers,this.add(a);let o=new rF(iF,1,e,t);o.layers=this.layers,this.add(o);let s=new rF(iF,1,e,t);s.layers=this.layers,this.add(s);let c=new rF(iF,1,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===$j)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else{if(e!==eM)throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1)}for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,i),e.setRenderTarget(n,1,r),e.render(t,a),e.setRenderTarget(n,2,r),e.render(t,o),e.setRenderTarget(n,3,r),e.render(t,s),e.setRenderTarget(n,4,r),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},oF=class extends BM{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},sF=class extends UM{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1};this.texture=new oF([n,n,n,n,n,n]),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}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;let n={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 ); + + } + `},r=new qP(5,5,5),i=new QP({name:`CubemapFromEquirect`,uniforms:JP(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new GP(r,i),o=t.minFilter;return t.minFilter===RA&&(t.minFilter=IA),new aF(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}},cF=class extends KN{constructor(){super(),this.isGroup=!0,this.type=`Group`}},lF={type:`move`},uF=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new cF,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 cF,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Q,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Q),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new cF,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Q,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Q),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){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}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,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position),s=.02,l=.005;c.inputState.pinching&&o>s+l?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=s-l&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(lF)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new cF;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},dF=class extends KN{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new kN,this.environmentIntensity=1,this.environmentRotation=new kN,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,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let 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.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},fF=class extends BM{constructor(e=null,t=1,n=1,r,i,a,o,s,c=1003,l=1003,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},pF=class extends SP{constructor(e,t,n,r=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},mF=new yN,hF=new yN,gF=[],_F=new KM,vF=new yN,yF=new GP,bF=new uN,xF=class extends GP{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new pF(new Float32Array(16*n),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let e=0;e1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<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){let n=t||wF.getNormalMatrix(e),r=this.coplanarPoint(SF).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),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)}},EF=new uN,DF=new xM(.5,.5),OF=new Q,kF=class{constructor(e=new TF,t=new TF,n=new TF,r=new TF,i=new TF,a=new TF){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===$j)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else{if(t!==eM)throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);r[5].setComponents(s,d,h,y).normalize()}return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),EF.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),EF.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(EF)}intersectsSprite(e){return EF.center.set(0,0,0),EF.radius=.7071067811865476+DF.distanceTo(e.center),EF.applyMatrix4(e.matrixWorld),this.intersectsSphere(EF)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,OF.y=r.normal.y>0?e.max.y:e.min.y,OF.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(OF)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},AF=class extends BM{constructor(e,t,n=1014,r,i,a,o=1003,s=1003,c,l=1026,u=1){if(l!==$A&&l!==ej)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new IM(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},jF=class extends BM{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},MF=class e extends NP{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e{t&&t(i),this.manager.itemEnd(e)},0),i;if(BF[e]!==void 0)return void BF[e].push({onLoad:t,onProgress:n,onError:r});BF[e]=[],BF[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&oM(`FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=BF[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){(function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e{e.error(t)})})()}});return new Response(c)}throw new VF(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{LF.add(`file:${e}`,t);let n=BF[e];delete BF[e];for(let e=0,r=n.length;e{let n=BF[e];if(n===void 0)throw this.manager.itemError(e),t;delete BF[e];for(let e=0,r=n.length;e{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},UF=new WeakMap,WF=class extends zF{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=LF.get(`image:${e}`);if(a!==void 0){if(!0===a.complete)i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);else{let e=UF.get(a);e===void 0&&(e=[],UF.set(a,e)),e.push({onLoad:t,onError:r})}return a}let o=nM(`img`);function s(){l(),t&&t(this);let n=UF.get(this)||[];for(let e=0;ee.start-t.start);let t=0;for(let e=1;e 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #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 +#endif`,clipping_planes_pars_fragment:`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,clipping_planes_pars_vertex:`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,clipping_planes_vertex:`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,color_fragment:`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,color_pars_fragment:`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,color_pars_vertex:`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,color_vertex:`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,common:`#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 ); +} +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`,cube_uv_reflection_fragment:`#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`,defaultnormal_vertex:`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`,displacementmap_pars_vertex:`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,displacementmap_vertex:`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,emissivemap_fragment:`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,emissivemap_pars_fragment:`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,colorspace_fragment:`gl_FragColor = linearToOutputTexel( gl_FragColor );`,colorspace_pars_fragment:`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +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 ); +}`,envmap_fragment:`#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, envMapRotation * 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`,envmap_common_pars_fragment:`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif +#endif`,envmap_pars_fragment:`#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`,envmap_pars_vertex:`#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`,envmap_physical_pars_fragment:`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * 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, pow4( roughness ) ) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * 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`,envmap_vertex:`#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`,fog_vertex:`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,fog_pars_vertex:`#ifdef USE_FOG + varying float vFogDepth; +#endif`,fog_fragment:`#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`,fog_pars_fragment:`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,gradientmap_pars_fragment:`#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 +}`,lightmap_pars_fragment:`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,lights_lambert_fragment:`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,lights_lambert_pars_fragment:`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`,lights_pars_begin:`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 ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +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`,lights_toon_fragment:`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,lights_toon_pars_fragment:`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`,lights_phong_fragment:`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,lights_phong_pars_fragment:`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`,lights_physical_fragment:`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_DISPERSION + material.dispersion = dispersion; +#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`,lights_physical_pars_fragment:`uniform sampler2D dfgLUT; +struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #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 * transpose( 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 ) ); + vec2 uv = vec2( roughness, dotNV ); + return texture2D( dfgLUT, uv ).rg; +} +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; +} +vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness ); + vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness ); + vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y; + vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y; + float Ess_V = dfgV.x + dfgV.y; + float Ess_L = dfgL.x + dfgL.y; + float Ems_V = 1.0 - Ess_V; + float Ems_L = 1.0 - Ess_L; + vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619; + vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON ); + float compensationFactor = Ems_V * Ems_L; + vec3 multiScatter = Fms * compensationFactor; + return singleScatter + multiScatter; +} +#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_Multiscatter( 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 ); +}`,lights_fragment_begin:` +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.shadowIntensity, 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.shadowIntensity, 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.shadowIntensity, 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`,lights_fragment_maps:`#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`,lights_fragment_end:`#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`,logdepthbuf_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,logdepthbuf_pars_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,logdepthbuf_pars_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,logdepthbuf_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,map_fragment:`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,map_pars_fragment:`#ifdef USE_MAP + uniform sampler2D map; +#endif`,map_particle_fragment:`#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`,map_particle_pars_fragment:`#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`,metalnessmap_fragment:`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,metalnessmap_pars_fragment:`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,morphinstance_vertex:`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,morphcolor_vertex:`#if defined( USE_MORPHCOLORS ) + 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`,morphnormal_vertex:`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,morphtarget_pars_vertex:`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + 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 ); + } +#endif`,morphtarget_vertex:`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,normal_fragment_begin:`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;`,normal_fragment_maps:`#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`,normal_pars_fragment:`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,normal_pars_vertex:`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,normal_vertex:`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,normalmap_pars_fragment:`#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`,clearcoat_normal_fragment_begin:`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,clearcoat_normal_fragment_maps:`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,clearcoat_pars_fragment:`#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`,iridescence_pars_fragment:`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,opaque_fragment:`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,packing:`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 float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in 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( const in 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 ); +}`,premultiplied_alpha_fragment:`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,project_vertex:`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;`,dithering_fragment:`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,dithering_pars_fragment:`#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`,roughnessmap_fragment:`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,roughnessmap_pars_fragment:`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,shadowmap_pars_fragment:`#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 shadowIntensity; + 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 shadowIntensity; + 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 shadowIntensity; + 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 ) { + float depth = unpackRGBAToDepth( texture2D( depths, uv ) ); + #ifdef USE_REVERSED_DEPTH_BUFFER + return step( depth, compare ); + #else + return step( compare, depth ); + #endif + } + 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 ); + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( distribution.x, compare ); + #else + float hard_shadow = step( compare, distribution.x ); + #endif + 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 shadowIntensity, 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 mix( 1.0, shadow, shadowIntensity ); + } + 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 shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + 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 + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,shadowmap_pars_vertex:`#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 shadowIntensity; + 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 shadowIntensity; + 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 shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,shadowmap_vertex:`#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`,shadowmask_pars_fragment:`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.shadowIntensity, 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.shadowIntensity, 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.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,skinbase_vertex:`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,skinning_pars_vertex:`#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`,skinning_vertex:`#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`,skinnormal_vertex:`#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`,specularmap_fragment:`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,specularmap_pars_fragment:`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,tonemapping_fragment:`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,tonemapping_pars_fragment:`#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 CineonToneMapping( 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 *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + 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; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,transmission_fragment:`#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.dispersion, 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`,transmission_pars_fragment:`#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 dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], 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 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + 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; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + 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`,uv_pars_fragment:`#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`,uv_pars_vertex:`#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`,uv_vertex:`#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`,worldpos_vertex:`#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`,background_vert:`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,background_frag:`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 +}`,backgroundCube_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,backgroundCube_frag:`#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; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,cube_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,cube_frag:`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 +}`,depth_vert:`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,depth_frag:`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,distanceRGBA_vert:`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,distanceRGBA_frag:`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,equirect_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,equirect_frag:`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,linedashed_vert:`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 + #include +}`,linedashed_frag:`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,meshbasic_vert:`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #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 +}`,meshbasic_frag:`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() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #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 +}`,meshlambert_vert:`#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 + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,meshlambert_frag:`#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() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + 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 +}`,meshmatcap_vert:`#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 + #include + vViewPosition = - mvPosition.xyz; +}`,meshmatcap_frag:`#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() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #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 +}`,meshnormal_vert:`#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 + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,meshnormal_frag:`#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() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,meshphong_vert:`#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 + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,meshphong_frag:`#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() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + 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 +}`,meshphysical_vert:`#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 + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,meshphysical_frag:`#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_DISPERSION + uniform float dispersion; +#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() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + 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 +}`,meshtoon_vert:`#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 + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,meshtoon_frag:`#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() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + 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 +}`,points_vert:`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 + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,points_frag:`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,shadow_vert:`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,shadow_frag:`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 +}`,sprite_vert:`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #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 +}`,sprite_frag:`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`},$={common:{diffuse:{value:new dP(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new TM},alphaMap:{value:null},alphaMapTransform:{value:new TM},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new TM}},envmap:{envMap:{value:null},envMapRotation:{value:new TM},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new TM}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new TM}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new TM},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new TM},normalScale:{value:new xM(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new TM},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new TM}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new TM}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new TM}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new dP(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,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 dP(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new TM},alphaTest:{value:0},uvTransform:{value:new TM}},sprite:{diffuse:{value:new dP(16777215)},opacity:{value:1},center:{value:new xM(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new TM},alphaMap:{value:null},alphaMapTransform:{value:new TM},alphaTest:{value:0}}},dI={basic:{uniforms:YP([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.fog]),vertexShader:uI.meshbasic_vert,fragmentShader:uI.meshbasic_frag},lambert:{uniforms:YP([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:new dP(0)}}]),vertexShader:uI.meshlambert_vert,fragmentShader:uI.meshlambert_frag},phong:{uniforms:YP([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:new dP(0)},specular:{value:new dP(1118481)},shininess:{value:30}}]),vertexShader:uI.meshphong_vert,fragmentShader:uI.meshphong_frag},standard:{uniforms:YP([$.common,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.roughnessmap,$.metalnessmap,$.fog,$.lights,{emissive:{value:new dP(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:uI.meshphysical_vert,fragmentShader:uI.meshphysical_frag},toon:{uniforms:YP([$.common,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.gradientmap,$.fog,$.lights,{emissive:{value:new dP(0)}}]),vertexShader:uI.meshtoon_vert,fragmentShader:uI.meshtoon_frag},matcap:{uniforms:YP([$.common,$.bumpmap,$.normalmap,$.displacementmap,$.fog,{matcap:{value:null}}]),vertexShader:uI.meshmatcap_vert,fragmentShader:uI.meshmatcap_frag},points:{uniforms:YP([$.points,$.fog]),vertexShader:uI.points_vert,fragmentShader:uI.points_frag},dashed:{uniforms:YP([$.common,$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:uI.linedashed_vert,fragmentShader:uI.linedashed_frag},depth:{uniforms:YP([$.common,$.displacementmap]),vertexShader:uI.depth_vert,fragmentShader:uI.depth_frag},normal:{uniforms:YP([$.common,$.bumpmap,$.normalmap,$.displacementmap,{opacity:{value:1}}]),vertexShader:uI.meshnormal_vert,fragmentShader:uI.meshnormal_frag},sprite:{uniforms:YP([$.sprite,$.fog]),vertexShader:uI.sprite_vert,fragmentShader:uI.sprite_frag},background:{uniforms:{uvTransform:{value:new TM},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:uI.background_vert,fragmentShader:uI.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new TM}},vertexShader:uI.backgroundCube_vert,fragmentShader:uI.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:uI.cube_vert,fragmentShader:uI.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:uI.equirect_vert,fragmentShader:uI.equirect_frag},distanceRGBA:{uniforms:YP([$.common,$.displacementmap,{referencePosition:{value:new Q},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:uI.distanceRGBA_vert,fragmentShader:uI.distanceRGBA_frag},shadow:{uniforms:YP([$.lights,$.fog,{color:{value:new dP(0)},opacity:{value:1}}]),vertexShader:uI.shadow_vert,fragmentShader:uI.shadow_frag}};dI.physical={uniforms:YP([dI.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new TM},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new TM},clearcoatNormalScale:{value:new xM(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new TM},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new TM},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new TM},sheen:{value:0},sheenColor:{value:new dP(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new TM},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new TM},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new TM},transmissionSamplerSize:{value:new xM},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new TM},attenuationDistance:{value:0},attenuationColor:{value:new dP(0)},specularColor:{value:new dP(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new TM},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new TM},anisotropyVector:{value:new xM},anisotropyMap:{value:null},anisotropyMapTransform:{value:new TM}}]),vertexShader:uI.meshphysical_vert,fragmentShader:uI.meshphysical_frag};var fI={r:0,b:0,g:0},pI=new kN,mI=new yN;function hI(e,t,n,r,i,a,o){let s=new dP(0),c,l,u=!0===a?0:1,d=null,f=0,p=null;function m(e){let r=!0===e.isScene?e.background:null;return r&&r.isTexture&&(r=(e.backgroundBlurriness>0?n:t).get(r)),r}function h(t,n){t.getRGB(fI,XP(e)),r.buffers.color.setClear(fI.r,fI.g,fI.b,n,o)}return{getClearColor:function(){return s},setClearColor:function(e,t=1){s.set(e),u=t,h(s,u)},getClearAlpha:function(){return u},setClearAlpha:function(e){u=e,h(s,u)},render:function(t){let n=!1,i=m(t);i===null?h(s,u):i&&i.isColor&&(h(i,1),n=!0);let a=e.xr.getEnvironmentBlendMode();a===`additive`?r.buffers.color.setClear(0,0,0,1,o):a===`alpha-blend`&&r.buffers.color.setClear(0,0,0,0,o),(e.autoClear||n)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){let r=m(n);r&&(r.isCubeTexture||r.mapping===kA)?(l===void 0&&(l=new GP(new qP(1,1,1),new QP({name:`BackgroundCubeMaterial`,uniforms:JP(dI.backgroundCube.uniforms),vertexShader:dI.backgroundCube.vertexShader,fragmentShader:dI.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,`envMap`,{get:function(){return this.uniforms.envMap.value}}),i.update(l)),pI.copy(n.backgroundRotation),pI.x*=-1,pI.y*=-1,pI.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(pI.y*=-1,pI.z*=-1),l.material.uniforms.envMap.value=r,l.material.uniforms.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(mI.makeRotationFromEuler(pI)),l.material.toneMapped=AM.getTransfer(r.colorSpace)!==Hj,d===r&&f===r.version&&p===e.toneMapping||(l.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):r&&r.isTexture&&(c===void 0&&(c=new GP(new MF(2,2),new QP({name:`BackgroundMaterial`,uniforms:JP(dI.background.uniforms),vertexShader:dI.background.vertexShader,fragmentShader:dI.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,`map`,{get:function(){return this.uniforms.t2D.value}}),i.update(c)),c.material.uniforms.t2D.value=r,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=AM.getTransfer(r.colorSpace)!==Hj,!0===r.matrixAutoUpdate&&r.updateMatrix(),c.material.uniforms.uvTransform.value.copy(r.matrix),d===r&&f===r.version&&p===e.toneMapping||(c.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))},dispose:function(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}}}function gI(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=l(null),a=i,o=!1;function s(t){return e.bindVertexArray(t)}function c(t){return e.deleteVertexArray(t)}function l(e){let t=[],r=[],i=[];for(let e=0;e=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}(n,h,c,g),_&&function(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}(n,h,c,g),g!==null&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||o)&&(o=!1,function(n,r,i,a){u();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,p=c.bytesPerElement,h=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===UA;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,g=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let o=n.precision===void 0?`highp`:n.precision,s=a(o);s!==o&&(oM(`WebGLRenderer:`,o,`not supported, using`,s,`instead.`),o=s);let c=!0===n.logarithmicDepthBuffer,l=!0===n.reversedDepthBuffer&&t.has(`EXT_clip_control`),u=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),d=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(i!==void 0)return i;if(!0===t.has(`EXT_texture_filter_anisotropic`)){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:a,textureFormatReadable:function(t){return t===QA||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){let i=n===KA&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==zA&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==GA&&!i)},precision:o,logarithmicDepthBuffer:c,reversedDepthBuffer:l,maxTextures:u,maxVertexTextures:d,maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:d>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function yI(e){let t=this,n=null,r=0,i=!1,a=!1,o=new TF,s=new TM,c={value:null,needsUpdate:!1};function l(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,!0!==i||l===null){let t=r+4*a,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length0),t.numPlanes=r,t.numIntersection=0}();else{let e=a?0:r,t=4*e,i=m.clippingState||null;c.value=i,i=l(d,s,t,u);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}}}function bI(e){let t=new WeakMap;function n(e,t){return t===OA?e.mapping=EA:t===304&&(e.mapping=DA),e}function r(e){let n=e.target;n.removeEventListener(`dispose`,r);let i=t.get(n);i!==void 0&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){let a=i.mapping;if(a===OA||a===304){if(t.has(i))return n(t.get(i).texture,i.mapping);{let a=i.image;if(a&&a.height>0){let o=new sF(a.height);return o.fromEquirectangularTexture(e,i),t.set(i,o),i.addEventListener(`dispose`,r),n(o.texture,i.mapping)}return null}}}return i},dispose:function(){t=new WeakMap}}}var xI=[.125,.215,.35,.446,.526,.582],SI=20,CI=new rI,wI=new dP,TI=null,EI=0,DI=0,OI=!1,kI=new Q,AI=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=kI}=i;TI=this._renderer.getRenderTarget(),EI=this._renderer.getActiveCubeFace(),DI=this._renderer.getActiveMipmapLevel(),OI=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=PI(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=NI(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?s=xI[o-e+4-1]:o===0&&(s=0),n.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new NP;h.setAttribute(`position`,new SP(f,3)),h.setAttribute(`uv`,new SP(p,2)),h.setAttribute(`faceIndex`,new SP(m,1)),r.push(new GP(h,null)),i>4&&i--}return{lodMeshes:r,sizeLods:t,sigmas:n}}(r)),this._blurMaterial=function(e,t,n){let r=new Float32Array(SI),i=new Q(0,1,0);return new QP({name:`SphericalGaussianBlur`,defines:{n:SI,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:FI(),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:0,depthTest:!1,depthWrite:!1})}(r,e,t)}return r}_compileMaterial(e){let t=new GP(new NP,e);this._renderer.compile(t,CI)}_sceneToCubeUV(e,t,n,r,i){let a=new rF(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(wI),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new GP(new qP,new hP({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(wI),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;MI(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===EA||e.mapping===DA;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=PI()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=NI());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i,i.uniforms.envMap.value=e;let o=this._cubeSize;MI(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(a,CI)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t + + #define PI 3.14159265359 + + // Van der Corput radical inverse + float radicalInverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 + } + + // Hammersley sequence + vec2 hammersley(uint i, uint N) { + return vec2(float(i) / float(N), radicalInverse_VdC(i)); + } + + // GGX VNDF importance sampling (Eric Heitz 2018) + // "Sampling the GGX Distribution of Visible Normals" + // https://jcgt.org/published/0007/04/01/ + vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { + float alpha = roughness * roughness; + + // Section 3.2: Transform view direction to hemisphere configuration + vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z)); + + // Section 4.1: Orthonormal basis + float lensq = Vh.x * Vh.x + Vh.y * Vh.y; + vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0); + vec3 T2 = cross(Vh, T1); + + // Section 4.2: Parameterization of projected area + float r = sqrt(Xi.x); + float phi = 2.0 * PI * Xi.y; + float t1 = r * cos(phi); + float t2 = r * sin(phi); + float s = 0.5 * (1.0 + Vh.z); + t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; + + // Section 4.3: Reprojection onto hemisphere + vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh; + + // Section 3.4: Transform back to ellipsoid configuration + return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); + } + + void main() { + vec3 N = normalize(vOutputDirection); + vec3 V = N; // Assume view direction equals normal for pre-filtering + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + // For very low roughness, just sample the environment directly + if (roughness < 0.001) { + gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); + return; + } + + // Tangent space basis for VNDF sampling + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { + vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); + + // For PMREM, V = N, so in tangent space V is always (0, 0, 1) + vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); + + // Transform H back to world space + vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); + vec3 L = normalize(2.0 * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.0); + + if(NdotL > 0.0) { + // Sample environment at fixed mip level + // VNDF importance sampling handles the distribution filtering + vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); + + // Weight by NdotL for the split-sum approximation + // VNDF PDF naturally accounts for the visible microfacet distribution + prefilteredColor += sampleColor * NdotL; + totalWeight += NdotL; + } + } + + if (totalWeight > 0.0) { + prefilteredColor = prefilteredColor / totalWeight; + } + + gl_FragColor = vec4(prefilteredColor, 1.0); + } + `,blending:0,depthTest:!1,depthWrite:!1})}(this._lodMax,e,t)}let a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(.05+.95*c),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-4?n-d+4:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,MI(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,CI),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,MI(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,CI)}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&sM(`blur direction must be either latitudinal or longitudinal!`);let l=this._lodMeshes[r];l.material=c;let u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/39,p=i/f,m=isFinite(i)?1+Math.floor(3*p):SI;m>SI&&oM(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);let h=[],g=0;for(let e=0;e_-4?r-_+4:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,CI)}};function jI(e,t,n){let r=new UM(e,t,n);return r.texture.mapping=kA,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function MI(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function NI(){return new QP({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:FI(),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:0,depthTest:!1,depthWrite:!1})}function PI(){return new QP({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:FI(),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:0,depthTest:!1,depthWrite:!1})}function FI(){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 II(e){let t=new WeakMap,n=null;function r(e){let n=e.target;n.removeEventListener(`dispose`,r);let i=t.get(n);i!==void 0&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){let a=i.mapping,o=a===OA||a===304,s=a===EA||a===DA;if(o||s){let a=t.get(i),c=a===void 0?0:a.texture.pmremVersion;if(i.isRenderTargetTexture&&i.pmremVersion!==c)return n===null&&(n=new AI(e)),a=o?n.fromEquirectangular(i,a):n.fromCubemap(i,a),a.texture.pmremVersion=i.pmremVersion,t.set(i,a),a.texture;if(a!==void 0)return a.texture;{let c=i.image;return o&&c&&c.height>0||s&&c&&function(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}(c)?(n===null&&(n=new AI(e)),a=o?n.fromEquirectangular(i):n.fromCubemap(i),a.texture.pmremVersion=i.pmremVersion,t.set(i,a),i.addEventListener(`dispose`,r),a.texture):null}}}return i},dispose:function(){t=new WeakMap,n!==null&&(n.dispose(),n=null)}}}function LI(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r=e.getExtension(n);return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&cM(`WebGLRenderer: `+e+` extension not supported.`),t}}}function RI(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),!0===s.isInstancedBufferGeometry&&delete s._maxInstanceCount,n.memory.geometries--}function s(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;tt.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let h=new Float32Array(p*m*4*u),g=new WM(h,p,m,u);g.type=GA,g.needsUpdate=!0;let _=4*f;for(let t=0;t0)return e;let i=t*n,a=JI[i];if(a===void 0&&(a=new Float32Array(i),JI[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function eL(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n`:` `} ${i}: ${n[e]}`)}return r.join(` +`)}(e.getShaderSource(t),r)}return i}function QL(e,t){let n=function(e){AM._getMatrix(XL,AM.workingColorSpace,e);let t=`mat3( ${XL.elements.map(e=>e.toFixed(4))} )`;switch(AM.getTransfer(e)){case Vj:return[t,`LinearTransferOETF`];case Hj:return[t,`sRGBTransferOETF`];default:return oM(`WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(` +`)}function $L(e,t){let n;switch(t){case 1:n=`Linear`;break;case 2:n=`Reinhard`;break;case 3:n=`Cineon`;break;case 4:n=`ACESFilmic`;break;case 6:n=`AgX`;break;case 7:n=`Neutral`;break;case 5:n=`Custom`;break;default:oM(`WebGLProgram: Unsupported toneMapping:`,t),n=`Linear`}return`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var eR=new Q;function tR(){return AM.getLuminanceCoefficients(eR),[`float luminance( const in vec3 rgb ) {`,`\tconst vec3 weights = vec3( ${eR.x.toFixed(4)}, ${eR.y.toFixed(4)}, ${eR.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(` +`)}function nR(e){return e!==``}function rR(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function iR(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var aR=/^[ \t]*#include +<([\w\d./]+)>/gm;function oR(e){return e.replace(aR,cR)}var sR=new Map;function cR(e,t){let n=uI[t];if(n===void 0){let e=sR.get(t);if(e===void 0)throw Error(`Can not resolve #include <`+t+`>`);n=uI[e],oM(`WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e)}return oR(n)}var lR=/#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 uR(e){return e.replace(lR,dR)}function dR(e,t,n,r){let i=``;for(let e=parseInt(t);e0&&(g+=` +`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(nR).join(` +`),_.length>0&&(_+=` +`)):(g=[fR(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&!1===n.flatShading?`#define USE_TANGENT`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&!1===n.flatShading?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`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`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#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`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,` +`].filter(nR).join(` +`),_=[fR(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&!1===n.flatShading?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor||n.batchingColor?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:uI.tonemapping_pars_fragment,n.toneMapping===0?``:$L(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,uI.colorspace_pars_fragment,QL(`linearToOutputTexel`,n.outputColorSpace),tR(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,` +`].filter(nR).join(` +`)),o=oR(o),o=rR(o,n),o=iR(o,n),s=oR(s),s=rR(s,n),s=iR(s,n),o=uR(o),s=uR(s),!0!==n.isRawShaderMaterial&&(v=`#version 300 es +`,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(` +`)+` +`+g,_=[`#define varying in`,n.glslVersion===Qj?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===Qj?``:`#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(` +`)+` +`+_);let y=v+g+o,b=v+_+s,x=JL(i,i.VERTEX_SHADER,y),S=JL(i,i.FRAGMENT_SHADER,b);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(!1===i.getProgramParameter(h,i.LINK_STATUS))if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=ZL(i,x,`vertex`),n=ZL(i,S,`fragment`);sM(`THREE.WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+` + +Material Name: `+t.name+` +Material Type: `+t.type+` + +Program Info Log: `+o+` +`+e+` +`+n)}else o===``?s!==``&&c!==``||(u=!1):oM(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new qL(i,h),T=function(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i0,ue=a.clearcoat>0,de=a.dispersion>0,fe=a.iridescence>0,pe=a.sheen>0,me=a.transmission>0,L=le&&!!a.anisotropyMap,he=ue&&!!a.clearcoatMap,R=ue&&!!a.clearcoatNormalMap,ge=ue&&!!a.clearcoatRoughnessMap,_e=fe&&!!a.iridescenceMap,ve=fe&&!!a.iridescenceThicknessMap,ye=pe&&!!a.sheenColorMap,be=pe&&!!a.sheenRoughnessMap,xe=!!a.specularMap,Se=!!a.specularColorMap,Ce=!!a.specularIntensityMap,we=me&&!!a.transmissionMap,Te=me&&!!a.thicknessMap,Ee=!!a.gradientMap,De=!!a.alphaMap,Oe=a.alphaTest>0,ke=!!a.alphaHash,Ae=!!a.extensions,je=0;a.toneMapped&&(j!==null&&!0!==j.isXRRenderTarget||(je=e.toneMapping));let Me={shaderID:C,shaderType:a.type,shaderName:a.name,vertexShader:E,fragmentShader:D,defines:a.defines,customVertexShaderID:O,customFragmentShaderID:k,isRawShaderMaterial:!0===a.isRawShaderMaterial,glslVersion:a.glslVersion,precision:p,batching:ee,batchingColor:ee&&_._colorsTexture!==null,instancing:N,instancingColor:N&&_.instanceColor!==null,instancingMorph:N&&_.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:j===null?e.outputColorSpace:!0===j.isXRRenderTarget?j.texture.colorSpace:Bj,alphaToCoverage:!!a.alphaToCoverage,map:te,matcap:P,envMap:F,envMapMode:F&&x.mapping,envMapCubeUVHeight:S,aoMap:ne,lightMap:re,bumpMap:I,normalMap:ie,displacementMap:f&&ae,emissiveMap:oe,normalMapObjectSpace:ie&&a.normalMapType===1,normalMapTangentSpace:ie&&a.normalMapType===0,metalnessMap:se,roughnessMap:ce,anisotropy:le,anisotropyMap:L,clearcoat:ue,clearcoatMap:he,clearcoatNormalMap:R,clearcoatRoughnessMap:ge,dispersion:de,iridescence:fe,iridescenceMap:_e,iridescenceThicknessMap:ve,sheen:pe,sheenColorMap:ye,sheenRoughnessMap:be,specularMap:xe,specularColorMap:Se,specularIntensityMap:Ce,transmission:me,transmissionMap:we,thicknessMap:Te,gradientMap:Ee,opaque:!1===a.transparent&&a.blending===1&&!1===a.alphaToCoverage,alphaMap:De,alphaTest:Oe,alphaHash:ke,combine:a.combine,mapUv:te&&h(a.map.channel),aoMapUv:ne&&h(a.aoMap.channel),lightMapUv:re&&h(a.lightMap.channel),bumpMapUv:I&&h(a.bumpMap.channel),normalMapUv:ie&&h(a.normalMap.channel),displacementMapUv:ae&&h(a.displacementMap.channel),emissiveMapUv:oe&&h(a.emissiveMap.channel),metalnessMapUv:se&&h(a.metalnessMap.channel),roughnessMapUv:ce&&h(a.roughnessMap.channel),anisotropyMapUv:L&&h(a.anisotropyMap.channel),clearcoatMapUv:he&&h(a.clearcoatMap.channel),clearcoatNormalMapUv:R&&h(a.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ge&&h(a.clearcoatRoughnessMap.channel),iridescenceMapUv:_e&&h(a.iridescenceMap.channel),iridescenceThicknessMapUv:ve&&h(a.iridescenceThicknessMap.channel),sheenColorMapUv:ye&&h(a.sheenColorMap.channel),sheenRoughnessMapUv:be&&h(a.sheenRoughnessMap.channel),specularMapUv:xe&&h(a.specularMap.channel),specularColorMapUv:Se&&h(a.specularColorMap.channel),specularIntensityMapUv:Ce&&h(a.specularIntensityMap.channel),transmissionMapUv:we&&h(a.transmissionMap.channel),thicknessMapUv:Te&&h(a.thicknessMap.channel),alphaMapUv:De&&h(a.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(ie||le),vertexColors:a.vertexColors,vertexAlphas:!0===a.vertexColors&&!!y.attributes.color&&y.attributes.color.itemSize===4,pointsUvs:!0===_.isPoints&&!!y.attributes.uv&&(te||De),fog:!!v,useFog:!0===a.fog,fogExp2:!!v&&v.isFogExp2,flatShading:!0===a.flatShading&&!1===a.wireframe,sizeAttenuation:!0===a.sizeAttenuation,logarithmicDepthBuffer:d,reversedDepthBuffer:M,skinning:!0===_.isSkinnedMesh,morphTargets:y.morphAttributes.position!==void 0,morphNormals:y.morphAttributes.normal!==void 0,morphColors:y.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:A,numDirLights:s.directional.length,numPointLights:s.point.length,numSpotLights:s.spot.length,numSpotLightMaps:s.spotLightMap.length,numRectAreaLights:s.rectArea.length,numHemiLights:s.hemi.length,numDirLightShadows:s.directionalShadowMap.length,numPointLightShadows:s.pointShadowMap.length,numSpotLightShadows:s.spotShadowMap.length,numSpotLightShadowsWithMaps:s.numSpotLightShadowsWithMaps,numLightProbes:s.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:a.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:je,decodeVideoTexture:te&&!0===a.map.isVideoTexture&&AM.getTransfer(a.map.colorSpace)===Hj,decodeVideoTextureEmissive:oe&&!0===a.emissiveMap.isVideoTexture&&AM.getTransfer(a.emissiveMap.colorSpace)===Hj,premultipliedAlpha:a.premultipliedAlpha,doubleSided:a.side===2,flipSided:a.side===1,useDepthPacking:a.depthPacking>=0,depthPacking:a.depthPacking||0,index0AttributeName:a.index0AttributeName,extensionClipCullDistance:Ae&&!0===a.extensions.clipCullDistance&&r.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Ae&&!0===a.extensions.multiDraw||ee)&&r.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:r.has(`KHR_parallel_shader_compile`),customProgramCacheKey:a.customProgramCacheKey()};return Me.vertexUv1s=l.has(1),Me.vertexUv2s=l.has(2),Me.vertexUv3s=l.has(3),l.clear(),Me},getProgramCacheKey:function(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){s.disableAll(),t.supportsVertexTextures&&s.enable(0),t.instancing&&s.enable(1),t.instancingColor&&s.enable(2),t.instancingMorph&&s.enable(3),t.matcap&&s.enable(4),t.envMap&&s.enable(5),t.normalMapObjectSpace&&s.enable(6),t.normalMapTangentSpace&&s.enable(7),t.clearcoat&&s.enable(8),t.iridescence&&s.enable(9),t.alphaTest&&s.enable(10),t.vertexColors&&s.enable(11),t.vertexAlphas&&s.enable(12),t.vertexUv1s&&s.enable(13),t.vertexUv2s&&s.enable(14),t.vertexUv3s&&s.enable(15),t.vertexTangents&&s.enable(16),t.anisotropy&&s.enable(17),t.alphaHash&&s.enable(18),t.batching&&s.enable(19),t.dispersion&&s.enable(20),t.batchingColor&&s.enable(21),t.gradientMap&&s.enable(22),e.push(s.mask),s.disableAll(),t.fog&&s.enable(0),t.useFog&&s.enable(1),t.flatShading&&s.enable(2),t.logarithmicDepthBuffer&&s.enable(3),t.reversedDepthBuffer&&s.enable(4),t.skinning&&s.enable(5),t.morphTargets&&s.enable(6),t.morphNormals&&s.enable(7),t.morphColors&&s.enable(8),t.premultipliedAlpha&&s.enable(9),t.shadowMapEnabled&&s.enable(10),t.doubleSided&&s.enable(11),t.flipSided&&s.enable(12),t.useDepthPacking&&s.enable(13),t.dithering&&s.enable(14),t.transmission&&s.enable(15),t.sheen&&s.enable(16),t.opaque&&s.enable(17),t.pointsUvs&&s.enable(18),t.decodeVideoTexture&&s.enable(19),t.decodeVideoTextureEmissive&&s.enable(20),t.alphaToCoverage&&s.enable(21),e.push(s.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){let t=m[e.type],n;if(t){let e=dI[t];n=ZP.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let r;for(let e=0,t=u.length;e0?r.push(u):!0===o.transparent?i.push(u):n.push(u)},unshift:function(e,t,o,s,c,l){let u=a(e,t,o,s,c,l);o.transmission>0?r.unshift(u):!0===o.transparent?i.unshift(u):n.unshift(u)},finish:function(){for(let n=t,r=e.length;n1&&n.sort(e||yR),r.length>1&&r.sort(t||bR),i.length>1&&i.sort(t||bR)}}}function SR(){let e=new WeakMap;return{get:function(t,n){let r=e.get(t),i;return r===void 0?(i=new xR,e.set(t,[i])):n>=r.length?(i=new xR,r.push(i)):i=r[n],i},dispose:function(){e=new WeakMap}}}function CR(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new Q,color:new dP};break;case`SpotLight`:n={position:new Q,direction:new Q,color:new dP,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new Q,color:new dP,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new Q,skyColor:new dP,groundColor:new dP};break;case`RectAreaLight`:n={color:new dP,position:new Q,halfWidth:new Q,halfHeight:new Q}}return e[t.id]=n,n}}}var wR=0;function TR(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function ER(e){let t=new CR,n=function(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new xM};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new xM,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),r={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 e=0;e<9;e++)r.probe.push(new Q);let i=new Q,a=new yN,o=new yN;return{setup:function(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(TR);for(let e=0,y=i.length;e0&&(!0===e.has(`OES_texture_float_linear`)?(r.rectAreaLTC1=$.LTC_FLOAT_1,r.rectAreaLTC2=$.LTC_FLOAT_2):(r.rectAreaLTC1=$.LTC_HALF_1,r.rectAreaLTC2=$.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;y.directionalLength===c&&y.pointLength===l&&y.spotLength===u&&y.rectAreaLength===d&&y.hemiLength===f&&y.numDirectionalShadows===p&&y.numPointShadows===m&&y.numSpotShadows===h&&y.numSpotMaps===g&&y.numLightProbes===v||(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=wR++)},setupView:function(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t=i.length?(a=new DR(e),i.push(a)):a=i[r],a},dispose:function(){t=new WeakMap}}}function kR(e,t,n){let r=new kF,i=new xM,a=new xM,o=new VM,s=new FF({depthPacking:3201}),c=new IF,l={},u=n.maxTextureSize,d={[Zk]:1,[Qk]:0,[$k]:2},f=new QP({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new xM},radius:{value:4}},vertexShader:`void main() { + gl_Position = vec4( position, 1.0 ); +}`,fragmentShader:`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 ) ); +}`}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new NP;m.setAttribute(`position`,new SP(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new GP(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new UM(i.x,i.y)),f.uniforms.shadow_pass.value=n.map.texture,f.uniforms.resolution.value=n.mapSize,f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=!0===r.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=!0===r.isPointLight?c:s,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}return a.visible=n.visible,a.wireframe=n.wireframe,a.side=i===3?n.shadowSide===null?n.side:n.shadowSide:n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,!0===r.isPointLight&&!0===a.isMeshDistanceMaterial&&(e.properties.get(a).light=r),a}function b(n,i,a,o,s){if(!1===n.visible)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;lu||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/h.x),i.x=a.x*h.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/h.y),i.y=a.y*h.y,d.mapSize.y=a.y)),d.map===null||!0===p||!0===m){let e=this.type===3?{}:{minFilter:NA,magFilter:NA};d.map!==null&&d.map.dispose(),d.map=new UM(i.x,i.y,e),d.map.texture.name=l.name+`.shadowMap`,d.camera.updateProjectionMatrix()}e.setRenderTarget(d.map),e.clear();let g=d.getViewportCount();for(let e=0;e=2):(A=parseFloat(/^WebGL (\d)/.exec(j)[1]),k=A>=1);let M=null,N={},ee=e.getParameter(e.SCISSOR_BOX),te=e.getParameter(e.VIEWPORT),P=new VM().fromArray(ee),F=new VM().fromArray(te);function ne(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;on||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);d===void 0&&(d=m(n,a));let o=t?m(n,a):d;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),oM(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}return`data`in e&&oM(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e}return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function y(n,r,i,a,o=!1){if(n!==null){if(e[n]!==void 0)return e[n];oM(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let s=r;if(r===e.RED&&(i===e.FLOAT&&(s=e.R32F),i===e.HALF_FLOAT&&(s=e.R16F),i===e.UNSIGNED_BYTE&&(s=e.R8)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.R8UI),i===e.UNSIGNED_SHORT&&(s=e.R16UI),i===e.UNSIGNED_INT&&(s=e.R32UI),i===e.BYTE&&(s=e.R8I),i===e.SHORT&&(s=e.R16I),i===e.INT&&(s=e.R32I)),r===e.RG&&(i===e.FLOAT&&(s=e.RG32F),i===e.HALF_FLOAT&&(s=e.RG16F),i===e.UNSIGNED_BYTE&&(s=e.RG8)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RG8UI),i===e.UNSIGNED_SHORT&&(s=e.RG16UI),i===e.UNSIGNED_INT&&(s=e.RG32UI),i===e.BYTE&&(s=e.RG8I),i===e.SHORT&&(s=e.RG16I),i===e.INT&&(s=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGB8UI),i===e.UNSIGNED_SHORT&&(s=e.RGB16UI),i===e.UNSIGNED_INT&&(s=e.RGB32UI),i===e.BYTE&&(s=e.RGB8I),i===e.SHORT&&(s=e.RGB16I),i===e.INT&&(s=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(s=e.RGBA16UI),i===e.UNSIGNED_INT&&(s=e.RGBA32UI),i===e.BYTE&&(s=e.RGBA8I),i===e.SHORT&&(s=e.RGBA16I),i===e.INT&&(s=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_INT_5_9_9_9_REV&&(s=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(s=e.R11F_G11F_B10F)),r===e.RGBA){let t=o?Vj:AM.getTransfer(a);i===e.FLOAT&&(s=e.RGBA32F),i===e.HALF_FLOAT&&(s=e.RGBA16F),i===e.UNSIGNED_BYTE&&(s=t===Hj?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT_4_4_4_4&&(s=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(s=e.RGB5_A1)}return s!==e.R16F&&s!==e.R32F&&s!==e.RG16F&&s!==e.RG32F&&s!==e.RGBA16F&&s!==e.RGBA32F||t.get(`EXT_color_buffer_float`),s}function b(t,n){let r;return t?n===null||n===WA||n===YA?r=e.DEPTH24_STENCIL8:n===GA?r=e.DEPTH32F_STENCIL8:n===HA&&(r=e.DEPTH24_STENCIL8,oM(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===WA||n===YA?r=e.DEPTH_COMPONENT24:n===GA?r=e.DEPTH_COMPONENT32F:n===HA&&(r=e.DEPTH_COMPONENT16),r}function x(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==NA&&e.minFilter!==IA?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function S(e){let t=e.target;t.removeEventListener(`dispose`,S),function(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=f.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&w(e),Object.keys(i).length===0&&f.delete(n)}r.remove(e)}(t),t.isVideoTexture&&u.delete(t)}function C(t){let n=t.target;n.removeEventListener(`dispose`,C),function(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r0&&a.__version!==t.version){let e=t.image;if(e===null)oM(`WebGLRenderer: Texture marked for update but no image data found.`);else{if(!1!==e.complete)return void N(a,t,i);oM(`WebGLRenderer: Texture marked for update but image is incomplete`)}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}let D={[AA]:e.REPEAT,[jA]:e.CLAMP_TO_EDGE,[MA]:e.MIRRORED_REPEAT},O={[NA]:e.NEAREST,[PA]:e.NEAREST_MIPMAP_NEAREST,[FA]:e.NEAREST_MIPMAP_LINEAR,[IA]:e.LINEAR,[LA]:e.LINEAR_MIPMAP_NEAREST,[RA]:e.LINEAR_MIPMAP_LINEAR},k={[Wj]:e.NEVER,[Zj]:e.ALWAYS,[Gj]:e.LESS,[qj]:e.LEQUAL,[Kj]:e.EQUAL,[Xj]:e.GEQUAL,[Jj]:e.GREATER,[Yj]:e.NOTEQUAL};function A(n,a){if(a.type!==GA||!1!==t.has(`OES_texture_float_linear`)||a.magFilter!==IA&&a.magFilter!==LA&&a.magFilter!==FA&&a.magFilter!==RA&&a.minFilter!==IA&&a.minFilter!==LA&&a.minFilter!==FA&&a.minFilter!==RA||oM(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,D[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,D[a.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,D[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,O[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,O[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,k[a.compareFunction])),!0===t.has(`EXT_texture_filter_anisotropic`)){if(a.magFilter===NA||a.minFilter!==FA&&a.minFilter!==RA||a.type===GA&&!1===t.has(`OES_texture_float_linear`))return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function j(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,S));let i=n.source,a=f.get(i);a===void 0&&(a={},f.set(i,a));let s=function(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&w(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function M(e,t,n){return Math.floor(Math.floor(e/n)/t)}function N(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=j(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let d=r.get(u);if(u.version!==d.__version||!0===l){n.activeTexture(e.TEXTURE0+s);let t=AM.getPrimaries(AM.workingColorSpace),r=o.colorSpace===Rj?null:AM.getPrimaries(o.colorSpace),f=o.colorSpace===Rj||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,f);let p=h(o.image,!1,i.maxTextureSize);p=ae(o,p);let m=a.convert(o.format,o.colorSpace),v=a.convert(o.type),S,C=y(o.internalFormat,m,v,o.colorSpace,o.isVideoTexture);A(c,o);let w=o.mipmaps,T=!0!==o.isVideoTexture,E=d.__version===void 0||!0===l,D=u.dataReady,O=x(o,p);if(o.isDepthTexture)C=b(o.format===ej,o.type),E&&(T?n.texStorage2D(e.TEXTURE_2D,1,C,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,C,p.width,p.height,0,m,v,null));else if(o.isDataTexture)if(w.length>0){T&&E&&n.texStorage2D(e.TEXTURE_2D,O,C,w[0].width,w[0].height);for(let t=0,r=w.length;te.start-t.start);let s=0;for(let e=1;e0){let r=sI(S.width,S.height,o.format,o.type);for(let i of o.layerUpdates){let a=S.data.subarray(i*r/S.data.BYTES_PER_ELEMENT,(i+1)*r/S.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,i,S.width,S.height,1,m,a)}o.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,m,S.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,C,S.width,S.height,p.depth,0,S.data,0,0);else oM(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else T?D&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,m,v,S.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,C,S.width,S.height,p.depth,0,m,v,S.data)}else{T&&E&&n.texStorage2D(e.TEXTURE_2D,O,C,w[0].width,w[0].height);for(let t=0,r=w.length;t0){let t=sI(p.width,p.height,o.format,o.type);for(let r of o.layerUpdates){let i=p.data.subarray(r*t/p.data.BYTES_PER_ELEMENT,(r+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,r,p.width,p.height,1,m,v,i)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,C,p.width,p.height,p.depth,0,m,v,p.data);else if(o.isData3DTexture)T?(E&&n.texStorage3D(e.TEXTURE_3D,O,C,p.width,p.height,p.depth),D&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,C,p.width,p.height,p.depth,0,m,v,p.data);else if(o.isFramebufferTexture){if(E)if(T)n.texStorage2D(e.TEXTURE_2D,O,C,p.width,p.height);else{let t=p.width,r=p.height;for(let i=0;i>=1,r>>=1}}else if(w.length>0){if(T&&E){let t=oe(w[0]);n.texStorage2D(e.TEXTURE_2D,O,C,t.width,t.height)}for(let t=0,r=w.length;t>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),ie(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,I(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function te(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=b(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,l=I(n);ie(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,l,o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,l,o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(a)throw Error(`target.depthTexture not supported in Cube render targets`);let e=t.texture.mipmaps;e&&e.length>0?P(i.__webglFramebuffer[0],t):P(i.__webglFramebuffer,t)}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),te(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),te(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}let ne=[],re=[];function I(e){return Math.min(i.maxSamples,e.samples)}function ie(e){let n=r.get(e);return e.samples>0&&!0===t.has(`WEBGL_multisampled_render_to_texture`)&&!1!==n.__useRenderToTexture}function ae(e,t){let n=e.colorSpace,r=e.format,i=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==Bj&&n!==Rj&&(AM.getTransfer(n)===Hj?r===QA&&i===zA||oM(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):sM(`WebGLTextures: Unsupported texture color space:`,n)),t}function oe(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=function(){let e=T;return e>=i.maxTextures&&oM(`WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+i.maxTextures),T+=1,e},this.resetTextureUnits=function(){T=0},this.setTexture2D=E,this.setTexture2DArray=function(t,i){let a=r.get(t);!1===t.isRenderTargetTexture&&t.version>0&&a.__version!==t.version?N(a,t,i):(t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i))},this.setTexture3D=function(t,i){let a=r.get(t);!1===t.isRenderTargetTexture&&t.version>0&&a.__version!==t.version?N(a,t,i):n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)},this.setTextureCube=function(t,o){let s=r.get(t);t.version>0&&s.__version!==t.version?function(t,o,s){if(o.image.length!==6)return;let c=j(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||!0===c){n.activeTexture(e.TEXTURE0+s);let t=AM.getPrimaries(AM.workingColorSpace),r=o.colorSpace===Rj?null:AM.getPrimaries(o.colorSpace),d=o.colorSpace===Rj||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)m[e]=f||p?p?o.image[e].image:o.image[e]:h(o.image[e],!0,i.maxCubemapSize),m[e]=ae(o,m[e]);let v=m[0],b=a.convert(o.format,o.colorSpace),S=a.convert(o.type),C=y(o.internalFormat,b,S,o.colorSpace),w=!0!==o.isVideoTexture,T=u.__version===void 0||!0===c,E=l.dataReady,D,O=x(o,v);if(A(e.TEXTURE_CUBE_MAP,o),f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,O,C,v.width,v.height);for(let t=0;t<6;t++){D=m[t].mipmaps;for(let r=0;r0&&O++;let t=oe(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,O,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,b,S,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,b,S,m[t].data);for(let r=0;r1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n0){s.__webglFramebuffer=[];for(let t=0;t0&&!1===ie(t)){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n0)for(let r=0;r0)for(let n=0;n0){if(!1===ie(t)){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new GP(new MF(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},FR=class extends lM{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new PR,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new xM,C=null,w=new rF;w.viewport=new VM;let T=new rF;T.viewport=new VM;let E=[w,T],D=new iI,O=null,k=null;function A(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function j(){r.removeEventListener(`select`,A),r.removeEventListener(`selectstart`,A),r.removeEventListener(`selectend`,A),r.removeEventListener(`squeeze`,A),r.removeEventListener(`squeezestart`,A),r.removeEventListener(`squeezeend`,A),r.removeEventListener(`end`,j),r.removeEventListener(`inputsourceschange`,M);for(let e=0;e=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t=x.length){x.push(n),r=e;break}if(x[e]===null){x[e]=n,r=e;break}}if(r===-1)break}let i=b[r];i&&i.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new uF,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new uF,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new uF,b[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){i=e,!0===n.isPresenting&&oM(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,!0===n.isPresenting&&oM(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,A),r.addEventListener(`selectstart`,A),r.addEventListener(`selectend`,A),r.addEventListener(`squeeze`,A),r.addEventListener(`squeezestart`,A),r.addEventListener(`squeezeend`,A),r.addEventListener(`end`,j),r.addEventListener(`inputsourceschange`,M),!0!==_.xrCompatible&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?ej:$A,a=_.stencil?YA:WA);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new UM(d.textureWidth,d.textureHeight,{format:QA,type:zA,depthTexture:new AF(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new UM(f.framebufferWidth,f.framebufferHeight,{format:QA,type:zA,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:!1===f.ignoreDepthValues,resolveStencilBuffer:!1===f.ignoreDepthValues})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),F.setContext(r),F.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};let N=new Q,ee=new Q;function te(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),D.near=T.near=w.near=t,D.far=T.far=w.far=n,O===D.near&&k===D.far||(r.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,k=D.far),D.layers.mask=6|e.layers.mask,w.layers.mask=3&D.layers.mask,T.layers.mask=5&D.layers.mask;let i=e.parent,a=D.cameras;te(D,i);for(let e=0;e0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,IR.copy(o),IR.x*=-1,IR.y*=-1,IR.z*=-1,a.isCubeTexture&&!1===a.isRenderTargetTexture&&(IR.y*=-1,IR.z*=-1),e.envMapRotation.value.setFromMatrix4(LR.makeRotationFromEuler(IR)),e.flipEnvMap.value=a.isCubeTexture&&!1===a.isRenderTargetTexture?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,XP(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,i,a,o,s){i.isMeshBasicMaterial||i.isMeshLambertMaterial?r(e,i):i.isMeshToonMaterial?(r(e,i),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,i)):i.isMeshPhongMaterial?(r(e,i),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,i)):i.isMeshStandardMaterial?(r(e,i),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,i),i.isMeshPhysicalMaterial&&function(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,i,s)):i.isMeshMatcapMaterial?(r(e,i),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,i)):i.isMeshDepthMaterial?r(e,i):i.isMeshDistanceMaterial?(r(e,i),function(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}(e,i)):i.isMeshNormalMaterial?r(e,i):i.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,i),i.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,i)):i.isPointsMaterial?function(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=.5*i,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i,a,o):i.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i):i.isShadowMaterial?(e.color.value.copy(i.color),e.opacity.value=i.opacity):i.isShaderMaterial&&(i.uniformsNeedUpdate=!1)}}}function zR(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return r[a]=typeof i==`number`||typeof i==`boolean`?i:i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(!1===e.equals(i))return e.copy(i),!0}return!1}function l(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?oM(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):oM(`WebGLRenderer: Unsupported uniform value type.`,e),t}function u(t){let n=t.target;n.removeEventListener(`dispose`,u);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}return{bind:function(e,t){let n=t.program;r.uniformBlockBinding(e,n)},update:function(n,d){let f=i[n.id];f===void 0&&(function(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e0&&(n+=16-r),e.__size=n,e.__cache={}}(n),f=function(t){let n=function(){for(let e=0;e0),d=!!n.morphAttributes.position,f=!!n.morphAttributes.normal,p=!!n.morphAttributes.color,m=0;r.toneMapped&&(T!==null&&!0!==T.isXRRenderTarget||(m=x.toneMapping));let h=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=h===void 0?0:h.length,_=R.get(r),y=v.state.lights;if(!0===ae&&(!0===oe||e!==D)){let t=e===D&&r.id===E;Ee.setState(r,e,t)}let b=!1;r.version===_.__version?_.needsLights&&_.lightsStateVersion!==y.state.version||_.outputColorSpace!==s||i.isBatchedMesh&&!1===_.batching?b=!0:i.isBatchedMesh||!0!==_.batching?i.isBatchedMesh&&!0===_.batchingColor&&i.colorTexture===null||i.isBatchedMesh&&!1===_.batchingColor&&i.colorTexture!==null||i.isInstancedMesh&&!1===_.instancing?b=!0:i.isInstancedMesh||!0!==_.instancing?i.isSkinnedMesh&&!1===_.skinning?b=!0:i.isSkinnedMesh||!0!==_.skinning?i.isInstancedMesh&&!0===_.instancingColor&&i.instanceColor===null||i.isInstancedMesh&&!1===_.instancingColor&&i.instanceColor!==null||i.isInstancedMesh&&!0===_.instancingMorph&&i.morphTexture===null||i.isInstancedMesh&&!1===_.instancingMorph&&i.morphTexture!==null||_.envMap!==c||!0===r.fog&&_.fog!==a?b=!0:_.numClippingPlanes===void 0||_.numClippingPlanes===Ee.numPlanes&&_.numIntersection===Ee.numIntersection?(_.vertexAlphas!==l||_.vertexTangents!==u||_.morphTargets!==d||_.morphNormals!==f||_.morphColors!==p||_.toneMapping!==m||_.morphTargetsCount!==g)&&(b=!0):b=!0:b=!0:b=!0:b=!0:(b=!0,_.__version=r.version);let S=_.currentProgram;!0===b&&(S=Qe(r,t,i));let C=!1,w=!1,O=!1,k=S.getUniforms(),A=_.uniforms;if(L.useProgram(S.program)&&(C=!0,w=!0,O=!0),r.id!==E&&(E=r.id,w=!0),C||D!==e){L.buffers.depth.getReversed()&&!0!==e.reversedDepth&&(e._reversedDepth=!0,e.updateProjectionMatrix()),k.setValue(z,`projectionMatrix`,e.projectionMatrix),k.setValue(z,`viewMatrix`,e.matrixWorldInverse);let t=k.map.cameraPosition;t!==void 0&&t.setValue(z,ce.setFromMatrixPosition(e.matrixWorld)),me.logarithmicDepthBuffer&&k.setValue(z,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&k.setValue(z,`isOrthographic`,!0===e.isOrthographicCamera),D!==e&&(D=e,w=!0,O=!0)}if(i.isSkinnedMesh){k.setOptional(z,i,`bindMatrix`),k.setOptional(z,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),k.setValue(z,`boneTexture`,e.boneTexture,ge))}i.isBatchedMesh&&(k.setOptional(z,i,`batchingTexture`),k.setValue(z,`batchingTexture`,i._matricesTexture,ge),k.setOptional(z,i,`batchingIdTexture`),k.setValue(z,`batchingIdTexture`,i._indirectTexture,ge),k.setOptional(z,i,`batchingColorTexture`),i._colorsTexture!==null&&k.setValue(z,`batchingColorTexture`,i._colorsTexture,ge));let j=n.morphAttributes;j.position===void 0&&j.normal===void 0&&j.color===void 0||ke.update(i,n,S),(w||_.receiveShadow!==i.receiveShadow)&&(_.receiveShadow=i.receiveShadow,k.setValue(z,`receiveShadow`,i.receiveShadow)),r.isMeshGouraudMaterial&&r.envMap!==null&&(A.envMap.value=c,A.flipEnvMap.value=c.isCubeTexture&&!1===c.isRenderTargetTexture?-1:1),r.isMeshStandardMaterial&&r.envMap===null&&t.environment!==null&&(A.envMapIntensity.value=t.environmentIntensity),A.dfgLUT!==void 0&&(A.dfgLUT.value=(VR===null&&(VR=new fF(BR,32,32,rj,KA),VR.minFilter=IA,VR.magFilter=IA,VR.wrapS=jA,VR.wrapT=jA,VR.generateMipmaps=!1,VR.needsUpdate=!0),VR)),w&&(k.setValue(z,`toneMappingExposure`,x.toneMappingExposure),_.needsLights&&(N=O,(M=A).ambientLightColor.needsUpdate=N,M.lightProbe.needsUpdate=N,M.directionalLights.needsUpdate=N,M.directionalLightShadows.needsUpdate=N,M.pointLights.needsUpdate=N,M.pointLightShadows.needsUpdate=N,M.spotLights.needsUpdate=N,M.spotLightShadows.needsUpdate=N,M.rectAreaLights.needsUpdate=N,M.hemisphereLights.needsUpdate=N),a&&!0===r.fog&&Ce.refreshFogUniforms(A,a),Ce.refreshMaterialUniforms(A,r,te,ee,v.state.transmissionRenderTarget[e.id]),qL.upload(z,$e(_),A,ge));var M,N;if(r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(qL.upload(z,$e(_),A,ge),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&k.setValue(z,`center`,i.center),k.setValue(z,`modelViewMatrix`,i.modelViewMatrix),k.setValue(z,`normalMatrix`,i.normalMatrix),k.setValue(z,`modelMatrix`,i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){let e=r.uniformsGroups;for(let t=0,n=e.length;t{function n(){r.forEach(function(e){R.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0?t(e):setTimeout(n,10)}pe.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let Ue=null;function We(){Ke.stop()}function Ge(){Ke.start()}let Ke=new cI;function qe(e,t,n,r){if(!1===e.visible)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)v.pushLight(e),e.castShadow&&v.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||ie.intersectsSprite(e)){r&&le.setFromMatrixPosition(e.matrixWorld).applyMatrix4(se);let t=xe.update(e),i=e.material;i.visible&&_.push(e,t,i,n,le.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||ie.intersectsObject(e))){let t=xe.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),le.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),le.copy(e.boundingSphere.center)),le.applyMatrix4(e.matrixWorld).applyMatrix4(se)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a0&&Xe(i,t,n),a.length>0&&Xe(a,t,n),o.length>0&&Xe(o,t,n),L.buffers.depth.setTest(!0),L.buffers.depth.setMask(!0),L.buffers.color.setMask(!0),L.setPolygonOffset(!1)}function Ye(e,t,n,r){if((!0===n.isScene?n.overrideMaterial:null)!==null)return;v.state.transmissionRenderTarget[r.id]===void 0&&(v.state.transmissionRenderTarget[r.id]=new UM(1,1,{generateMipmaps:!0,type:pe.has(`EXT_color_buffer_half_float`)||pe.has(`EXT_color_buffer_float`)?KA:zA,minFilter:RA,samples:4,stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:AM.workingColorSpace}));let a=v.state.transmissionRenderTarget[r.id],o=r.viewport||O;a.setSize(o.z*x.transmissionResolutionScale,o.w*x.transmissionResolutionScale);let s=x.getRenderTarget(),c=x.getActiveCubeFace(),l=x.getActiveMipmapLevel();x.setRenderTarget(a),x.getClearColor(j),M=x.getClearAlpha(),M<1&&x.setClearColor(16777215,.5),x.clear(),de&&Oe.render(n);let u=x.toneMapping;x.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),v.setupLightsView(r),!0===ae&&Ee.setGlobalState(x.clippingPlanes,r),Xe(e,n,r),ge.updateMultisampleRenderTarget(a),ge.updateRenderTargetMipmap(a),!1===pe.has(`WEBGL_multisampled_render_to_texture`)){let e=!1;for(let i=0,a=t.length;i0)for(let t=0,a=n.length;t0&&Ye(r,i,e,t),de&&Oe.render(e),Je(_,e,t);T!==null&&w===0&&(ge.updateMultisampleRenderTarget(T),ge.updateRenderTargetMipmap(T)),!0===e.isScene&&e.onAfterRender(x,e,t),Ne.resetDefaultState(),E=-1,D=null,b.pop(),b.length>0?(v=b[b.length-1],!0===ae&&Ee.setGlobalState(x.clippingPlanes,v.state.camera)):v=null,y.pop(),_=y.length>0?y[y.length-1]:null},this.getActiveCubeFace=function(){return C},this.getActiveMipmapLevel=function(){return w},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(e,t,n){let r=R.get(e);r.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===r.__autoAllocateDepthBuffer&&(r.__useRenderToTexture=!1),R.get(e.texture).__webglTexture=t,R.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=R.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let tt=z.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){T=e,C=t,w=n;let r=!0,i=null,a=!1,o=!1;if(e){let s=R.get(e);if(s.__useDefaultFramebuffer!==void 0)L.bindFramebuffer(z.FRAMEBUFFER,null),r=!1;else if(s.__webglFramebuffer===void 0)ge.setupRenderTarget(e);else if(s.__hasExternalTextures)ge.rebindTextures(e,R.get(e.texture).__webglTexture,R.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(s.__boundDepthTexture!==t){if(t!==null&&R.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);ge.setupDepthRenderbuffer(e)}}let c=e.texture;(c.isData3DTexture||c.isDataArrayTexture||c.isCompressedArrayTexture)&&(o=!0);let l=R.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],a=!0):i=e.samples>0&&!1===ge.useMultisampledRTT(e)?R.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,O.copy(e.viewport),k.copy(e.scissor),A=e.scissorTest}else O.copy(ne).multiplyScalar(te).floor(),k.copy(re).multiplyScalar(te).floor(),A=I;if(n!==0&&(i=tt),L.bindFramebuffer(z.FRAMEBUFFER,i)&&r&&L.drawBuffers(e,i),L.viewport(O),L.scissor(k),L.setScissorTest(A),a){let r=R.get(e.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(o){let r=t;for(let t=0;t=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+s),z.readPixels(t,n,r,i,Me.convert(c),Me.convert(l),a))}finally{let e=T===null?null:R.get(T).__webglFramebuffer;L.bindFramebuffer(z.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!e||!e.isWebGLRenderTarget)throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=R.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){L.bindFramebuffer(z.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(!me.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!me.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,d),z.bufferData(z.PIXEL_PACK_BUFFER,a.byteLength,z.STREAM_READ),e.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+s),z.readPixels(t,n,r,i,Me.convert(l),Me.convert(u),0);let f=T===null?null:R.get(T).__webglFramebuffer;L.bindFramebuffer(z.FRAMEBUFFER,f);let p=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await function(e,t,n){return new Promise(function(r,i){setTimeout(function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}},n)})}(z,p,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,d),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,a),z.deleteBuffer(d),z.deleteSync(p),a}throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)}},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;ge.setTexture2D(e,0),z.copyTexSubImage2D(z.TEXTURE_2D,n,0,0,o,s,i,a),L.unbindTexture()};let nt=z.createFramebuffer(),rt=z.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=null){let o,s,c,l,u,d,f,p,m;a===null&&(i===0?a=0:(cM(`WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.`),a=i,i=0));let h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Me.convert(t.format),_=Me.convert(t.type),v;t.isData3DTexture?(ge.setTexture3D(t,0),v=z.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(ge.setTexture2DArray(t,0),v=z.TEXTURE_2D_ARRAY):(ge.setTexture2D(t,0),v=z.TEXTURE_2D),z.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,t.flipY),z.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),z.pixelStorei(z.UNPACK_ALIGNMENT,t.unpackAlignment);let y=z.getParameter(z.UNPACK_ROW_LENGTH),b=z.getParameter(z.UNPACK_IMAGE_HEIGHT),x=z.getParameter(z.UNPACK_SKIP_PIXELS),S=z.getParameter(z.UNPACK_SKIP_ROWS),C=z.getParameter(z.UNPACK_SKIP_IMAGES);z.pixelStorei(z.UNPACK_ROW_LENGTH,h.width),z.pixelStorei(z.UNPACK_IMAGE_HEIGHT,h.height),z.pixelStorei(z.UNPACK_SKIP_PIXELS,l),z.pixelStorei(z.UNPACK_SKIP_ROWS,u),z.pixelStorei(z.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=R.get(e),r=R.get(t),h=R.get(n.__renderTarget),g=R.get(r.__renderTarget);L.bindFramebuffer(z.READ_FRAMEBUFFER,h.__webglFramebuffer),L.bindFramebuffer(z.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n{};onAfterRender=()=>{};onAfterResize=()=>{};#n=!1;#r=!1;isDisposed=!1;#i;#a;#o;#s=new aI;#c={elapsed:0,delta:0};#l;#u;#d=0;#f=0;constructor(e){this.#e={...e},this.#p(),this.#m(),this.#h(),this.resize(),this.#g()}#p(){this.camera=new rF,this.cameraFov=this.camera.fov}#m(){this.scene=new dF}#h(){this.#e.canvas?this.canvas=this.#e.canvas:this.#e.id?this.canvas=document.getElementById(this.#e.id):console.error(`Three: Missing canvas or id parameter`),this.canvas.style.display=`block`,this.canvas.style.touchAction=`none`,this.renderer=new HR({canvas:this.canvas,powerPreference:`high-performance`,...this.#e.rendererOptions??{}}),this.renderer.outputColorSpace=zj}#g(){this.#e.size instanceof Object||(window.addEventListener(`resize`,this.#b.bind(this)),this.#e.size===`parent`&&(this.#a=new ResizeObserver(this.#b.bind(this)),this.#a.observe(this.canvas.parentNode))),this.#i=new IntersectionObserver(this.#v.bind(this),{root:null,rootMargin:`0px`,threshold:0}),this.#i.observe(this.canvas),document.addEventListener(`visibilitychange`,this.#y.bind(this))}#_(){window.removeEventListener(`resize`,this.#b.bind(this)),this.#a?.disconnect(),this.#i?.disconnect(),document.removeEventListener(`visibilitychange`,this.#y.bind(this))}#v(e){this.#n=e[0].isIntersecting,this.#n?this.#w():this.#T()}#y(e){this.#n&&(document.hidden?this.#T():this.#w())}#b(){this.#o&&clearTimeout(this.#o),this.#o=setTimeout(this.resize.bind(this),100)}resize(){let e,t;this.#e.size instanceof Object?(e=this.#e.size.width,t=this.#e.size.height):this.#e.size===`parent`&&this.canvas.parentNode?(e=this.canvas.parentNode.offsetWidth,t=this.canvas.parentNode.offsetHeight):(e=window.innerWidth,t=window.innerHeight),this.size.width=e,this.size.height=t,this.size.ratio=e/t,this.#x(),this.#C(),this.onAfterResize(this.size)}#x(){this.camera.aspect=this.size.width/this.size.height,this.camera.isPerspectiveCamera&&this.cameraFov&&(this.cameraMinAspect&&this.camera.aspectthis.cameraMaxAspect?this.#S(this.cameraMaxAspect):this.camera.fov=this.cameraFov),this.camera.updateProjectionMatrix(),this.updateWorldSize()}#S(e){let t=Math.tan(bM.degToRad(this.cameraFov/2))/(this.camera.aspect/e);this.camera.fov=2*bM.radToDeg(Math.atan(t))}updateWorldSize(){if(this.camera.isPerspectiveCamera){let e=this.camera.fov*Math.PI/180;this.size.wHeight=2*Math.tan(e/2)*this.camera.position.length(),this.size.wWidth=this.size.wHeight*this.camera.aspect}else this.camera.isOrthographicCamera&&(this.size.wHeight=this.camera.top-this.camera.bottom,this.size.wWidth=this.camera.right-this.camera.left)}#C(){this.renderer.setSize(this.size.width,this.size.height),this.#t?.setSize(this.size.width,this.size.height);let e=window.devicePixelRatio;this.maxPixelRatio&&e>this.maxPixelRatio?e=this.maxPixelRatio:this.minPixelRatio&&e0?1/e:0}#w(){if(this.#r)return;let e=()=>{this.#l=requestAnimationFrame(e),this.#c.elapsed=this.#s.getElapsedTime();let t=this.#c.elapsed-this.#f;(!this.#u||this.#u&&t>this.#d)&&(this.#c.delta=t,this.onBeforeRender(this.#c),this.render(),this.onAfterRender(this.#c),this.#f=this.#c.elapsed)};this.#r=!0,this.#s.start(),e()}#T(){this.#r&&(cancelAnimationFrame(this.#l),this.#r=!1,this.#s.stop(),this.#f=0)}#E(){this.renderer.render(this.scene,this.camera)}clear(){this.scene.traverse(e=>{e.isMesh&&typeof e.material==`object`&&(Object.keys(e.material).forEach(t=>{let n=e.material[t];typeof n==`object`&&n&&typeof n.dispose==`function`&&n.dispose()}),e.material.dispose(),e.geometry.dispose())}),this.scene.clear()}dispose(){this.#_(),this.#T(),this.clear(),this.#t?.dispose(),this.renderer.dispose(),this.isDisposed=!0}},WR=new Map,GR=new xM,KR,qR,JR=!1;function YR(e){let t={position:new xM,nPosition:new xM,hover:!1,pressed:!1,onEnter(){},onLeave(){},onMove(){},onDown(){},onUp(){},onClick(){},...e};return function(e,t){WR.has(e)||(WR.set(e,t),JR||=(document.body.addEventListener(`pointermove`,ZR),document.body.addEventListener(`pointerleave`,QR),document.body.addEventListener(`pointerdown`,$R),document.body.addEventListener(`pointerup`,ez),document.body.addEventListener(`click`,tz),!0))}(e.domElement,t),t.dispose=()=>{var t=e.domElement;WR.delete(t),WR.size===0&&(document.body.removeEventListener(`pointermove`,ZR),document.body.removeEventListener(`pointerleave`,QR),document.body.removeEventListener(`pointerdown`,$R),document.body.removeEventListener(`pointerup`,ez),document.body.removeEventListener(`click`,tz),JR=!1)},t}function XR(e,t){GR.x=e.clientX,GR.y=e.clientY;for(let[e,n]of WR)t(n,e.getBoundingClientRect())}function ZR(e){XR(e,(t,n)=>{rz(n)?(nz(t,n),t.hover||(t.hover=!0,t.onEnter(t)),t.pressed=e.buttons>0,t.onMove(t)):t.hover&&(t.hover=!1,t.pressed=!1,t.onLeave(t))})}function QR(){for(let e of WR.values())e.hover&&(e.hover=!1,e.onLeave(e))}function $R(e){XR(e,(e,t)=>{rz(t)&&(nz(e,t),e.onDown(e))})}function ez(e){XR(e,(e,t)=>{rz(t)&&(nz(e,t),e.onUp(e))})}function tz(e){XR(e,(e,t)=>{rz(t)&&(nz(e,t),e.onClick(e))})}function nz(e,t){let{position:n,nPosition:r}=e;n.x=GR.x-t.left,n.y=GR.y-t.top,r.x=n.x/t.width*2-1,r.y=-n.y/t.height*2+1}function rz(e){let{x:t,y:n}=GR,{left:r,top:i,width:a,height:o}=e;return t>=r&&t<=r+a&&n>=i&&n<=i+o}var iz=class extends GF{constructor(e){super(e),this.type=KA}parse(e){let t=function(e,t){switch(e){case 1:throw Error(`THREE.HDRLoader: Read Error: `+(t||``));case 2:throw Error(`THREE.HDRLoader: Write Error: `+(t||``));case 3:throw Error(`THREE.HDRLoader: Bad File Format: `+(t||``));default:throw Error(`THREE.HDRLoader: Memory Error: `+(t||``))}},n=function(e,t,n){t||=1024;let r=e.pos,i=-1,a=0,o=``,s=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));for(;0>(i=s.indexOf(` +`))&&a=e.byteLength||!(c=n(e)))&&t(1,`no header found`),(l=c.match(/^#\?(\S+)/))||t(3,`bad initial token`),s.valid|=1,s.programtype=l[1],s.string+=c+` +`;c=n(e),!1!==c;)if(s.string+=c+` +`,c.charAt(0)!==`#`){if((l=c.match(r))&&(s.gamma=parseFloat(l[1])),(l=c.match(i))&&(s.exposure=parseFloat(l[1])),(l=c.match(a))&&(s.valid|=2,s.format=l[1]),(l=c.match(o))&&(s.valid|=4,s.height=parseInt(l[1],10),s.width=parseInt(l[2],10)),2&s.valid&&4&s.valid)break}else s.comments+=c+` +`;return 2&s.valid||t(3,`missing format specifier`),4&s.valid||t(3,`missing image size specifier`),s}(a),s=o.width,c=o.height,l=function(e,n,r){let i=n;if(i<8||i>32767||e[0]!==2||e[1]!==2||128&e[2])return new Uint8Array(e);i!==(e[2]<<8|e[3])&&t(3,`wrong scanline width`);let a=new Uint8Array(4*n*r);a.length||t(4,`unable to allocate buffer space`);let o=0,s=0,c=4*i,l=new Uint8Array(4),u=new Uint8Array(c),d=r;for(;d>0&&se.byteLength&&t(1),l[0]=e[s++],l[1]=e[s++],l[2]=e[s++],l[3]=e[s++],l[0]==2&&l[1]==2&&(l[2]<<8|l[3])==i||t(3,`bad rgbe scanline format`);let n,r=0;for(;r128;if(i&&(n-=128),(n===0||r+n>c)&&t(3,`bad scanline data`),i){let t=e[s++];for(let e=0;e{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}};function sz(e){return new PF({color:0,emissive:16777215,emissiveIntensity:e})}var cz=new rI(-1,1,1,-1,0,1),lz=new class extends NP{constructor(){super(),this.setAttribute(`position`,new TP([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute(`uv`,new TP([0,2,0,0,2,0],2))}},uz=class{constructor(e){this._mesh=new GP(lz,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,cz)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}},dz=`varying vec2 vUv;void main(){vUv=uv;gl_Position=vec4(position,1.0);}`,fz=512,pz=class{#e;#t;#n;attenuation;#r;#i;#a;#o;#s;#c;#l;#u=[];constructor({renderer:e}){this.#e=e,this.#t={value:1},this.#n={value:new xM(1/fz,1/fz)},this.attenuation={value:.995},this.#d(),this.#f()}#d(){let e={minFilter:IA,magFilter:IA,type:GA,format:QA,depthBuffer:!1,stencilBuffer:!1};this.#r=new UM(fz,fz,e),this.#i=new UM(fz,fz,e),this.#a=new uz}#f(){this.#o=new QP({uniforms:{tDiffuse:{value:null}},vertexShader:dz,fragmentShader:`uniform sampler2D tDiffuse;varying vec2 vUv;void main(){gl_FragColor=texture2D(tDiffuse,vUv);}`}),this.#s=new QP({uniforms:{tDiffuse:{value:null},texelSize:this.#n,attenuation:this.attenuation},vertexShader:dz,fragmentShader:`uniform sampler2D tDiffuse;uniform vec2 texelSize;uniform float attenuation;varying vec2 vUv;void main(){vec4 texel=texture2D(tDiffuse,vUv);vec2 dx=vec2(texelSize.x,0.0);vec2 dy=vec2(0.0,texelSize.y);float average=(texture2D(tDiffuse,vUv-dx).r+texture2D(tDiffuse,vUv-dy).r+texture2D(tDiffuse,vUv+dx).r+texture2D(tDiffuse,vUv+dy).r)*0.25;texel.g+=(average-texel.r)*2.0;texel.g*=attenuation;texel.r+=texel.g;gl_FragColor=texel;}`}),this.#c=new QP({uniforms:{tDiffuse:{value:null},texelSize:this.#n},vertexShader:dz,fragmentShader:`uniform sampler2D tDiffuse;uniform vec2 texelSize;varying vec2 vUv;void main(){vec4 texel=texture2D(tDiffuse,vUv);vec3 dx=vec3(texelSize.x,0.0,texture2D(tDiffuse,vec2(vUv.x+texelSize.x,vUv.y)).r-texel.r);vec3 dy=vec3(0.0,texelSize.y,texture2D(tDiffuse,vec2(vUv.x,vUv.y+texelSize.y)).r-texel.r);texel.ba=normalize(cross(dx,dy)).xy;gl_FragColor=texel;}`}),this.#l=new QP({uniforms:{tDiffuse:{value:null},aspectRatio:this.#t,center:new oI(new xM),radius:{value:.05},strength:{value:.5}},vertexShader:dz,fragmentShader:`const float PI=3.1415926535897932384626433832795;uniform sampler2D tDiffuse;uniform float aspectRatio;uniform vec2 center;uniform float radius;uniform float strength;varying vec2 vUv;void main(){vec4 texel=texture2D(tDiffuse,vUv);vec2 p=center*0.5+0.5-vUv;p.x*=aspectRatio;float drop=max(0.0,1.0-length(p)/radius);drop=0.5-cos(drop*PI)*0.5;texel.r+=drop*strength;gl_FragColor=texel;}`})}get texture(){return this.#r.texture}setSize({width:e,height:t,ratio:n}){let r=e,i=t;e>t?(r=fz,i=Math.floor(fz/e*t)):(i=fz,r=Math.floor(fz/t*e)),this.#t.value=n,this.#n.value.set(1/r,1/i),this.#r.setSize(r,i),this.#i.setSize(r,i)}update(){let e=this.#e.getRenderTarget();this.#h(),this.#p(),this.#m(),this.#e.setRenderTarget(e)}#p(){this.#s.uniforms.tDiffuse.value=this.#r.texture,this.#_(this.#s,this.#i),this.#v()}#m(){this.#c.uniforms.tDiffuse.value=this.#r.texture,this.#_(this.#c,this.#i),this.#v()}addDrop(e,t,n,r){this.#u.push({x:e,y:t,radius:n,strength:r})}#h(){for(let e=0;e1?n*this.#t.value:n,this.#l.uniforms.strength.value=r,this.#_(this.#l,this.#i),this.#v()}#_(e,t){this.#a.material=e,this.#e.setRenderTarget(t),this.#a.render(this.#e)}#v(){let e=this.#r;this.#r=this.#i,this.#i=e}dispose(){this.#o.dispose(),this.#s.dispose(),this.#c.dispose(),this.#l.dispose(),this.#r.dispose(),this.#i.dispose()}},mz=class extends GP{#e;#t=1;constructor({renderer:e}){super(new MF(1,1,1,1),new NF({metalness:.75,roughness:.5})),this.rotation.x=-Math.PI/2,this.#e=new pz({renderer:e}),this.uniforms={uvMapScale:{value:new xM(1,1)},displacementMap:{value:this.#e.texture},displacementScale:{value:1}},this.material.defines={USE_UV:``},this.material.onBeforeCompile=e=>{Object.assign(e.uniforms,this.uniforms),e.fragmentShader=` + uniform vec2 uvMapScale; + uniform sampler2D displacementMap; + uniform float displacementScale; + + float redOffset = 0.01; + float greenOffset = 0.02; + float blueOffset = 0.03; + `+e.fragmentShader,e.fragmentShader=e.fragmentShader.replace(`#include `,` + vec4 disp = texture2D(displacementMap, vUv); + vec3 transformedNormal = vec3(disp.b, disp.a, sqrt(1.0 - dot(disp.ba, disp.ba))); + #ifdef USE_MAP + // vec2 newUv = ((vUv - 0.5) * uvMapScale + 0.5) + transformedNormal.xy * transformedNormal.z * displacementScale * 0.02; + vec2 dUv = transformedNormal.xy * displacementScale * 0.02; + vec2 newUv = ((vUv - 0.5) * uvMapScale + 0.5) + dUv; + float st = smoothstep(0.0, 0.1, length(dUv)); + diffuseColor.r *= texture2D(map, newUv + redOffset * st).r; + diffuseColor.g *= texture2D(map, newUv + greenOffset * st).g; + diffuseColor.b *= texture2D(map, newUv + blueOffset * st).b; + // vec4 sampledDiffuseColor = texture2D(map, newUv); + // diffuseColor *= sampledDiffuseColor; + #endif + `),e.fragmentShader=e.fragmentShader.replace(`#include `,` + normal = transformedNormal; + `)};let t=new AI(e).fromScene(new oz,.04).texture;this.material.envMap=t}get attenuation(){return this.#e.attenuation.value}set attenuation(e){this.#e.attenuation.value=e}update(){this.#e.update()}addDrop(e,t,n,r){this.#e.addDrop(e,t,n,r)}setImage(e){this.material.map=e,this.material.needsUpdate=!0,this.#n()}#n(){let e=this.material.map;if(e&&e.image){let t=e.image.width/e.image.height;this.#t{r.addDrop(a.nPosition.x,a.nPosition.y,.025,.0025)},a.onClick=()=>{r.addDrop(a.nPosition.x,a.nPosition.y,.025,.05)},n.onBeforeRender=e=>{i.enable&&(i.time+=e.delta,i.time>i.timeDelta&&(r.addDrop(hz(2),hz(2),gz(.01,.02),gz(.001,.005)),i.time=0)),r.update()},n.onAfterResize=e=>{r.setSize(e)},{three:n,liquidPlane:r,async loadImage(e){if(e){let t=await az(e);t.colorSpace=zj,r.setImage(t)}else r.setImage(null)},async loadEnvMap(e){if(e){let t=await az(e);t.colorSpace=zj,t.mapping=OA,r.setEnvMap(t)}else r.setEnvMap(null)},setRain(e){i.enable=e},setRainTime(e){i.timeDelta=e},dispose:()=>{a.dispose(),r.dispose(),n.dispose()}}}function vz({onEnter:e}){let t=(0,f.useRef)(null),n=(0,f.useRef)(null),[r,i]=(0,f.useState)(!1),[a,o]=(0,f.useState)(!1);return(0,f.useEffect)(()=>{let e=!1;async function r(){if(e||!t.current)return;let r=_z(t.current);n.current=r,r.loadImage(`/gemma4.png`),r.liquidPlane.material.metalness=.82,r.liquidPlane.material.roughness=.48,r.liquidPlane.uniforms.displacementScale.value=6,r.setRain(!1),setTimeout(()=>{e||o(!0)},300)}return r(),()=>{e=!0,n.current&&=(n.current.dispose(),null)}},[]),(0,Z.jsxs)(`div`,{className:`absolute inset-0 z-30 cursor-pointer bg-black`,onClick:(0,f.useCallback)(()=>{r||(i(!0),setTimeout(()=>{n.current&&=(n.current.dispose(),null),e()},600))},[r,e]),children:[(0,Z.jsx)(`canvas`,{ref:t,className:`absolute inset-0 w-full h-full transition-opacity duration-700 ${a?`opacity-100`:`opacity-0`}`}),(0,Z.jsxs)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-end transition-opacity duration-500 pb-10 ${r?`opacity-0`:a?`opacity-100`:`opacity-0`}`,children:[(0,Z.jsxs)(`h1`,{className:`text-6xl sm:text-7xl font-bold tracking-tight select-none drop-shadow-[0_2px_12px_rgba(0,0,0,0.5)]`,children:[(0,Z.jsx)(`span`,{className:`text-white`,children:`Gemma 4`}),` `,(0,Z.jsx)(`span`,{className:`text-white/90`,children:`WebGPU`})]}),(0,Z.jsx)(`p`,{className:`mt-6 text-lg text-white/80 select-none animate-pulse-gentle drop-shadow-[0_1px_6px_rgba(0,0,0,0.5)]`,children:`Click anywhere to start`})]}),(0,Z.jsx)(`div`,{className:`absolute inset-0 bg-black transition-opacity duration-600 pointer-events-none ${r?`opacity-100`:`opacity-0`}`})]})}var yz=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),bz=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),xz=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Sz=e=>{let t=xz(e);return t.charAt(0).toUpperCase()+t.slice(1)},Cz={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},wz=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Tz=(0,f.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,f.createElement)(`svg`,{ref:c,...Cz,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:yz(`lucide`,i),...!a&&!wz(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,f.createElement)(e,t)),...Array.isArray(a)?a:[a]])),Ez=(e,t)=>{let n=(0,f.forwardRef)(({className:n,...r},i)=>(0,f.createElement)(Tz,{ref:i,iconNode:t,className:yz(`lucide-${bz(Sz(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Sz(e),n},Dz=Ez(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),Oz=Ez(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),kz=Ez(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Az=Ez(`triangle-alert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),jz=Ez(`upload`,[[`path`,{d:`M12 3v12`,key:`1x0j5s`}],[`path`,{d:`m17 8-5-5-5 5`,key:`7q97r8`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}]]),Mz=Ez(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);function Nz({status:e}){let t=e.state===`ready`?100:e.state===`loading`&&typeof e.progress==`number`?e.progress:0,n=e.state===`loading`?e.message??`Loading model...`:e.state===`error`?`Failed to load model`:`Initializing...`;return(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center bg-[#0a0a0a] text-white animate-fade-in`,children:(0,Z.jsxs)(`div`,{className:`w-full max-w-md px-6 flex flex-col items-center`,children:[(0,Z.jsxs)(`div`,{className:`mb-10 flex items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`w-9 h-9 rounded-lg bg-[#1a73e8] flex items-center justify-center`,children:(0,Z.jsxs)(`svg`,{viewBox:`0 0 100 100`,className:`w-5 h-5`,children:[(0,Z.jsx)(`polygon`,{points:`50,10 85,35 72,85 28,85 15,35`,fill:`rgba(255,255,255,0.95)`}),(0,Z.jsx)(`polygon`,{points:`50,10 62,35 50,85 38,35`,fill:`rgba(255,255,255,0.55)`})]})}),(0,Z.jsx)(`span`,{className:`text-lg font-medium tracking-tight`,children:`Gemma 4`})]}),e.state!==`error`&&(0,Z.jsx)(Oz,{className:`h-8 w-8 animate-spin text-[#1a73e8] mb-4`}),(0,Z.jsx)(`p`,{className:`text-sm tracking-wide ${e.state===`error`?`text-red-400 font-medium`:`text-white/70`}`,children:n}),(0,Z.jsx)(`div`,{className:`mt-6 h-1 w-full rounded-full bg-white/10 overflow-hidden`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-[#1a73e8] transition-[width] duration-300 ease-out`,style:{width:`${t}%`}})}),(0,Z.jsx)(`p`,{className:`mt-4 text-xs text-white/40`,children:`Cached after first load · Runs 100% offline`}),e.state===`error`&&(0,Z.jsx)(`p`,{className:`mt-3 text-sm text-red-400 text-center`,children:e.error})]})})}function Pz(){let e=(0,f.useContext)(Vk);if(!e)throw Error(`useLLM must be used inside `);return e}var Fz=384;function Iz(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let e=new Image;e.onload=()=>{let{width:n,height:r}=e;if(n>Fz||r>Fz){let e=Fz/Math.max(n,r);n=Math.round(n*e),r=Math.round(r*e)}let i=document.createElement(`canvas`);i.width=n,i.height=r,i.getContext(`2d`).drawImage(e,0,0,n,r),t(i.toDataURL(`image/jpeg`,.9))},e.onerror=n,e.src=r.result},r.onerror=n,r.readAsDataURL(e)})}async function Lz(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status} for ${e}`);let n=await t.blob();return Iz(new File([n],`image.jpg`,{type:n.type}))}function Rz({onImageSelect:e,currentImage:t,disabled:n}){let r=(0,f.useRef)(null),[i,a]=(0,f.useState)(!1),o=(0,f.useCallback)(async t=>{if(!t.type.startsWith(`image/`)){console.warn(`[Gemma4] Ignoring non-image file:`,t.type);return}try{e(await Iz(t))}catch(e){console.error(`[Gemma4] Failed to read image:`,e),alert(`Failed to read image: ${e instanceof Error?e.message:String(e)}`)}},[e]),s=(0,f.useCallback)(e=>{e.preventDefault(),a(!1);let t=e.dataTransfer.files[0];t&&o(t)},[o]),c=(0,f.useCallback)(e=>{let t=e.clipboardData.items;for(let e of t)if(e.type.startsWith(`image/`)){let t=e.getAsFile();t&&o(t);break}},[o]);return t?(0,Z.jsxs)(`div`,{className:`relative group`,children:[(0,Z.jsx)(`img`,{src:t,alt:`Selected`,className:`w-full max-h-[400px] object-contain rounded-xl border border-white/10`}),!n&&(0,Z.jsx)(`button`,{onClick:()=>e(``),className:`absolute top-2 right-2 p-1.5 rounded-lg bg-black/60 text-white/70 hover:text-white hover:bg-red-500/80 transition-colors opacity-0 group-hover:opacity-100`,children:(0,Z.jsx)(Mz,{className:`h-4 w-4`})})]}):(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),a(!0)},onDragLeave:()=>a(!1),onDrop:s,onPaste:c,tabIndex:0,className:`flex flex-col items-center justify-center gap-4 rounded-2xl border-2 border-dashed p-10 transition-all cursor-pointer ${i?`border-[#1a73e8] bg-[#1a73e8]/10`:`border-white/10 hover:border-white/30 bg-white/5`} ${n?`opacity-50 pointer-events-none`:``}`,onClick:()=>r.current?.click(),children:[(0,Z.jsx)(`div`,{className:`flex h-16 w-16 items-center justify-center rounded-2xl bg-[#1a73e8]/10 border border-white/10`,children:i?(0,Z.jsx)(jz,{className:`h-8 w-8 text-[#1a73e8]`}):(0,Z.jsx)(Dz,{className:`h-8 w-8 text-[#1a73e8]`})}),(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`p`,{className:`text-base font-medium text-white`,children:i?`Drop image here`:`Upload an image`}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-white/60`,children:`Drag & drop, click to browse, or paste from clipboard`})]}),(0,Z.jsx)(`input`,{ref:r,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&o(t),e.target.value=``}})]})}var zz=`Detect all objects in this image. Return each detection as JSON: [{"box_2d": [y1, x1, y2, x2], "label": "object_name"}]`,Bz=zz,Vz=`Describe this image in detail. What objects, people, and activities do you see?`,Hz=`https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main`,Uz=[{url:`${Hz}/cats.jpg`,prompt:Bz,label:`Cats`},{url:`${Hz}/city-streets.jpg`,prompt:Bz,label:`Streets`},{url:`${Hz}/corgi.jpg`,prompt:Bz,label:`Corgi`},{url:`${Hz}/football-match.jpg`,prompt:Bz,label:`Football`},{url:`${Hz}/airport.jpg`,prompt:Bz,label:`Airport`},{url:`${Hz}/butterfly.jpg`,prompt:Vz,label:`Butterfly`}];function Wz({onSelect:e,disabled:t}){return(0,Z.jsxs)(`div`,{className:t?`opacity-50 pointer-events-none`:``,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-white/60 mb-3`,children:`Or try an example:`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-3 sm:grid-cols-6 gap-3`,children:Uz.map(t=>(0,Z.jsxs)(`button`,{onClick:()=>e(t.url,t.prompt),className:`group relative overflow-hidden rounded-xl border border-white/10 bg-white/5 transition-all hover:border-[#1a73e8]/60 hover:shadow-lg hover:shadow-[#1a73e8]/20 cursor-pointer`,children:[(0,Z.jsx)(`div`,{className:`aspect-square overflow-hidden`,children:(0,Z.jsx)(`img`,{src:t.url,alt:t.label,className:`w-full h-full object-cover transition-transform duration-300 group-hover:scale-110`,loading:`lazy`})}),(0,Z.jsx)(`div`,{className:`absolute inset-0 bg-gradient-to-t from-black/70 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end p-2`,children:(0,Z.jsx)(`span`,{className:`text-xs font-medium text-white`,children:t.label})})]},t.label))})]})}function Gz({imageUrl:e,detections:t}){let n=(0,f.useRef)(null),r=(0,f.useRef)(null);return(0,f.useEffect)(()=>{let e=n.current,i=r.current;if(!e||!i||!i.complete)return;let a=e.getContext(`2d`);if(!a)return;let o=i.getBoundingClientRect();e.width=o.width,e.height=o.height,a.clearRect(0,0,e.width,e.height);let s=[...new Set(t.map(e=>e.label))];for(let n of t){let[t,r,i,o]=Wk(n.box_2d,e.width,e.height),c=Gk[s.indexOf(n.label)%Gk.length];a.strokeStyle=c,a.lineWidth=2.5,a.strokeRect(t,r,i-t,o-r),a.font=`bold 13px 'Google Sans', sans-serif`;let l=a.measureText(n.label).width,u=Math.max(0,r-20);a.fillStyle=c,a.beginPath(),a.roundRect(t,u,l+10,20,4),a.fill(),a.fillStyle=`#ffffff`,a.fillText(n.label,t+5,u+14)}},[t]),(0,Z.jsxs)(`div`,{className:`relative inline-block w-full`,children:[(0,Z.jsx)(`img`,{ref:r,src:e,alt:`Detection result`,className:`w-full max-h-[500px] object-contain rounded-xl`,onLoad:()=>{if(t.length>0){let e=n.current,i=r.current;if(!e||!i)return;let a=e.getContext(`2d`);if(!a)return;let o=i.getBoundingClientRect();e.width=o.width,e.height=o.height,a.clearRect(0,0,e.width,e.height);let s=[...new Set(t.map(e=>e.label))];for(let n of t){let[t,r,i,o]=Wk(n.box_2d,e.width,e.height),c=Gk[s.indexOf(n.label)%Gk.length];a.strokeStyle=c,a.lineWidth=2.5,a.strokeRect(t,r,i-t,o-r),a.font=`bold 13px 'Google Sans', sans-serif`;let l=a.measureText(n.label).width,u=Math.max(0,r-20);a.fillStyle=c,a.beginPath(),a.roundRect(t,u,l+10,20,4),a.fill(),a.fillStyle=`#ffffff`,a.fillText(n.label,t+5,u+14)}}}}),(0,Z.jsx)(`canvas`,{ref:n,className:`absolute top-0 left-0 w-full h-full pointer-events-none`,style:{objectFit:`contain`}})]})}function Kz({result:e,isGenerating:t,tps:n}){return!e&&!t?null:(0,Z.jsxs)(`div`,{className:`rounded-2xl border border-white/10 bg-white/5 p-4 sm:p-5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium text-white/60`,children:t?(0,Z.jsx)(`span`,{className:`detection-shimmer`,children:`Analyzing image...`}):`${e?.detections.length??0} object(s) detected`}),n>0&&(0,Z.jsxs)(`span`,{className:`text-xs text-white/50 font-mono`,children:[n,` tok/s`]})]}),t&&!e?.text&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-[#1a73e8]`,children:[(0,Z.jsx)(Oz,{className:`h-4 w-4 animate-spin`}),(0,Z.jsx)(`span`,{className:`text-sm`,children:`Processing...`})]}),e?.text&&(0,Z.jsx)(`pre`,{className:`text-sm text-white/80 whitespace-pre-wrap break-words font-mono leading-relaxed bg-black/40 rounded-xl p-3 max-h-[200px] overflow-y-auto`,children:e.text}),e&&e.detections.length>0&&!t&&(0,Z.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:e.detections.map((e,t)=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 rounded-lg bg-[#1a73e8]/15 border border-[#1a73e8]/40 px-2.5 py-1 text-xs font-medium text-[#8bb4f0]`,children:[(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full bg-[#1a73e8]`}),e.label]},t))})]})}function qz(){let{detect:e,isGenerating:t,tps:n,dtype:r,result:i,stop:a}=Pz(),[o,s]=(0,f.useState)(null),[c,l]=(0,f.useState)(zz),[u,d]=(0,f.useState)(!1),p=(0,f.useCallback)(t=>{if(!t){s(null);return}s(t),e(t,c)},[e,c]),m=(0,f.useCallback)(async(t,n)=>{d(!0);try{let r=await Lz(t);s(r),l(n),e(r,n)}catch(e){console.error(`[Gemma4] Failed to load example:`,e),alert(`Failed to load example image (likely CORS):\n${e instanceof Error?e.message:String(e)}`)}d(!1)},[e]),h=(0,f.useCallback)(()=>{o&&e(o,c)},[o,c,e]);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full bg-[#0a0a0a] text-white animate-fade-in`,children:[(0,Z.jsxs)(`header`,{className:`flex items-center justify-between px-4 py-3 sm:px-6 border-b border-white/10`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium tracking-tight`,children:`Gemma 4`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t&&(0,Z.jsx)(`button`,{onClick:a,className:`px-3 py-1.5 text-xs font-medium rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer`,children:`Stop`}),o&&!t&&(0,Z.jsx)(`button`,{onClick:h,className:`p-1.5 rounded-lg hover:bg-white/5 transition-colors text-white/60 hover:text-white cursor-pointer`,title:`Retry detection`,children:(0,Z.jsx)(kz,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-4 sm:p-6`,children:(0,Z.jsxs)(`div`,{className:`max-w-4xl mx-auto space-y-6`,children:[r===`q4`&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 rounded-xl border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-200`,children:[(0,Z.jsx)(Az,{className:`h-5 w-5 shrink-0 mt-0.5 text-amber-400`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:`Running on q4 (slow path) — inference may fail with OOM on 8GB GPUs.`}),(0,Z.jsxs)(`p`,{className:`mt-1 text-amber-200/70 text-xs leading-relaxed`,children:[`For faster, stabler inference, enable`,` `,(0,Z.jsx)(`code`,{className:`font-mono bg-amber-500/20 px-1 rounded`,children:`chrome://flags/#enable-unsafe-webgpu`}),` and`,` `,(0,Z.jsx)(`code`,{className:`font-mono bg-amber-500/20 px-1 rounded`,children:`chrome://flags/#enable-vulkan`}),`, then fully restart Chrome.`]})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-sm font-medium text-white/60 mb-2`,children:`Prompt`}),(0,Z.jsx)(`textarea`,{value:c,onChange:e=>l(e.target.value),rows:2,disabled:t,className:`w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white placeholder-white/30 focus:border-[#1a73e8] focus:outline-none focus:ring-1 focus:ring-[#1a73e8] resize-none disabled:opacity-50`,placeholder:`Enter your prompt...`})]}),o?(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[i&&i.detections.length>0?(0,Z.jsx)(Gz,{imageUrl:o,detections:i.detections}):(0,Z.jsx)(`img`,{src:o,alt:`Uploaded`,className:`w-full max-h-[500px] object-contain rounded-xl border border-white/10`}),(0,Z.jsx)(Kz,{result:i,isGenerating:t,tps:n}),!t&&(0,Z.jsx)(`button`,{onClick:()=>s(null),className:`w-full py-3 rounded-xl border border-white/10 text-sm font-medium text-white/60 hover:text-white hover:border-white/30 transition-colors cursor-pointer`,children:`Try another image`})]}):(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(Rz,{onImageSelect:p,currentImage:null,disabled:t||u}),(0,Z.jsx)(Wz,{onSelect:m,disabled:t||u})]})]})})]})}function Jz(){let{status:e,loadModel:t}=Pz(),[n,r]=(0,f.useState)(`intro`),i=e.state===`ready`;return(0,f.useEffect)(()=>{n===`loading`&&i&&r(`app`)},[n,i]),(0,Z.jsxs)(`div`,{className:`relative h-screen w-screen bg-[#0a0a0a] text-white`,children:[n===`intro`&&(0,Z.jsx)(vz,{onEnter:()=>{r(`loading`),t()}}),n===`loading`&&(0,Z.jsx)(Nz,{status:e}),n===`app`&&(0,Z.jsx)(qz,{})]})}(0,p.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(f.StrictMode,{children:(0,Z.jsx)(Yk,{children:(0,Z.jsx)(Jz,{})})})); \ No newline at end of file