mjswan 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -58,7 +58,7 @@ ${o?`${s(`light`)}{${o}}`:``}`}function Qn({color:e,theme:t,autoContrast:n}){ret
58
58
  Prefix can't start with '-' when allowNegative is true.
59
59
  prefix: `+i+`
60
60
  allowNegative: `+a+`
61
- `),a=!1),Object.assign(Object.assign({},e),{allowNegative:a})}function dh(e){e=uh(e),e.decimalSeparator,e.allowedDecimalSeparators,e.thousandsGroupStyle;var t=e.suffix,n=e.allowNegative,r=e.allowLeadingZeros,i=e.onKeyDown;i===void 0&&(i=Em);var a=e.onBlur;a===void 0&&(a=Em);var o=e.thousandSeparator,s=e.decimalScale,c=e.fixedDecimalScale,l=e.prefix;l===void 0&&(l=``);var u=e.defaultValue,d=e.value,f=e.valueIsNumericString,p=e.onValueChange,m=wm(e,[`decimalSeparator`,`allowedDecimalSeparators`,`thousandsGroupStyle`,`suffix`,`allowNegative`,`allowLeadingZeros`,`onKeyDown`,`onBlur`,`thousandSeparator`,`decimalScale`,`fixedDecimalScale`,`prefix`,`defaultValue`,`value`,`valueIsNumericString`,`onValueChange`]),h=ih(e),g=h.decimalSeparator,_=h.allowedDecimalSeparators,v=function(t){return rh(t,e)},y=function(t,n){return ch(t,n,e)},b=km(d)?u:d,x=f??sh(b,l,t);km(d)?km(u)||(x||=typeof u==`number`):x||=typeof d==`number`;var S=function(e){return jm(e)?e:(typeof e==`number`&&(e=Bm(e)),x&&typeof s==`number`?Vm(e,s,!!c):e)},C=$m(S(d),S(u),!!x,v,y,p),w=C[0],T=w.numAsString,E=w.formattedValue,D=C[1];return Object.assign(Object.assign({},m),{value:E,valueIsNumericString:!1,isValidInputCharacter:function(e){return e===g?!0:Om(e)},isCharacterSame:function(e){var t=e.currentValue,n=e.lastValue,r=e.formattedValue,i=e.currentValueIndex,a=e.formattedValueIndex,o=t[i],u=r[a],f=Um(n,t).to,p=function(e){return y(e).indexOf(`.`)+l.length};return d===0&&c&&s&&t[f.start]===g&&p(t)<i&&p(r)>a?!1:i>=f.start&&i<f.end&&_&&_.includes(o)&&u===g?!0:o===u},onValueChange:D,format:v,removeFormatting:y,getCaretBoundary:function(t){return lh(t,e)},onKeyDown:function(e){var t=e.target,r=e.key,a=t.selectionStart,u=t.selectionEnd,d=t.value;if(d===void 0&&(d=``),(r===`Backspace`||r===`Delete`)&&u<l.length&&d!==`-`){e.preventDefault();return}if(a!==u){i(e);return}r===`Backspace`&&d[0]===`-`&&a===l.length+1&&n&&Hm(t,1),s&&c&&(r===`Backspace`&&d[a-1]===g?(Hm(t,a-1),e.preventDefault()):r===`Delete`&&d[a]===g&&e.preventDefault()),_?.includes(r)&&d[a]===g&&Hm(t,a+1);var f=o===!0?`,`:o;r===`Backspace`&&d[a-1]===f&&Hm(t,a-1),r===`Delete`&&d[a]===f&&Hm(t,a+1),i(e)},onBlur:function(t){var n=T;n.match(/\d/g)||(n=``),r||(n=Lm(n)),c&&s&&(n=Vm(n,s,c)),n!==T&&D({formattedValue:rh(n,e),value:n,floatValue:parseFloat(n)},{event:t,source:Tm.event}),a(t)}})}function fh(e){var t=dh(e);return b.createElement(nh,Object.assign({},t))}var ph={root:`m_e2f5cd4e`,controls:`m_95e17d22`,control:`m_80b4b171`};function mh({direction:e,style:t,...n}){return(0,G.jsx)(`svg`,{style:{width:`var(--ni-chevron-size)`,height:`var(--ni-chevron-size)`,transform:e===`up`?`rotate(180deg)`:void 0,...t},viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...n,children:(0,G.jsx)(`path`,{d:`M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}var hh=/^(0\.0*|-0(\.0*)?)$/,gh=/^-?0\d+(\.\d+)?\.?$/,_h=/\.\d*0$/,vh=/^-?\d+\.$/;function yh(e){return typeof e==`string`&&e!==``&&!Number.isNaN(Number(e))}function bh(e){return typeof e==`number`?e<2**53-1:e===``||yh(e)&&Number(e)<2**53-1}function xh(e){return e.toString().replace(`.`,``).length}function Sh(e,t){return(typeof e==`number`?e<2**53-1:!Number.isNaN(Number(e)))&&!Number.isNaN(e)&&xh(t)<14&&t!==``}function Ch(e,t,n){return e===void 0?!0:(t===void 0||e>=t)&&(n===void 0||e<=n)}var wh={step:1,clampBehavior:`blur`,allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0,allowedDecimalSeparators:[`.`,`,`]},Th=en((e,{size:t})=>({controls:{"--ni-chevron-size":nt(t,`ni-chevron-size`)}}));function Eh(e,t,n){let r=e.toString(),i=vh.test(r),a=r.replace(/^0+(?=\d)/,``),o=parseFloat(a);if(Number.isNaN(o))return a;if(o>2**53-1)return t===void 0?a:t;let s=ut(o,n,t);return i?`${s.toString().replace(/^0+(?=\d)/,``)}.`:s}var Dh=_i((e,t)=>{let n=K(`NumberInput`,wh,e),{className:r,classNames:i,styles:a,unstyled:o,vars:s,onChange:c,onValueChange:l,value:u,defaultValue:d,max:f,min:p,step:m,hideControls:h,rightSection:g,isAllowed:_,clampBehavior:v,onBlur:y,allowDecimal:x,decimalScale:S,onKeyDown:C,onKeyDownCapture:w,handlersRef:T,startValue:E,disabled:D,rightSectionPointerEvents:O,allowNegative:k,readOnly:A,size:j,rightSectionWidth:M,stepHoldInterval:N,stepHoldDelay:P,allowLeadingZeros:F,withKeyboardEvents:I,trimLeadingZeroesOnBlur:L,allowedDecimalSeparators:R,attributes:z,...B}=n,V=jr({name:`NumberInput`,classes:ph,props:n,classNames:i,styles:a,unstyled:o,attributes:z,vars:s,varsResolver:Th}),{resolvedClassNames:ee,resolvedStyles:te}=mr({classNames:i,styles:a,props:n}),[ne,re]=Vt({value:u,defaultValue:d,finalValue:``,onChange:c}),ie=P!==void 0&&N!==void 0,ae=(0,b.useRef)(null),oe=(0,b.useRef)(null),se=(0,b.useRef)(0),H=(e,t)=>{t.source===`event`&&re(Sh(e.floatValue,e.value)&&!hh.test(e.value)&&!(F&&gh.test(e.value))&&!_h.test(e.value)&&!vh.test(e.value)?e.floatValue:e.value),l?.(e,t)},ce=e=>{let t=String(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0},le=e=>{ae.current&&e!==void 0&&ae.current.setSelectionRange(e,e)},ue=(0,b.useRef)(et);ue.current=()=>{if(!bh(ne))return;let e,t=ce(ne),n=ce(m),r=Math.max(t,n),i=10**r;if(!yh(ne)&&(typeof ne!=`number`||Number.isNaN(ne)))e=ut(E,p,f);else if(f!==void 0){let t=(Math.round(Number(ne)*i)+Math.round(m*i))/i;e=t<=f?t:f}else e=(Math.round(Number(ne)*i)+Math.round(m*i))/i;let a=e.toFixed(r);re(parseFloat(a)),l?.({floatValue:parseFloat(a),formattedValue:a,value:a},{source:`increment`}),setTimeout(()=>le(ae.current?.value.length),0)};let U=(0,b.useRef)(et);U.current=()=>{if(!bh(ne))return;let e,t=p===void 0?k?-(2**53-1):0:p,n=ce(ne),r=ce(m),i=Math.max(n,r),a=10**i;if(!yh(ne)&&typeof ne!=`number`||Number.isNaN(ne))e=ut(E,t,f);else{let n=(Math.round(Number(ne)*a)-Math.round(m*a))/a;e=t!==void 0&&n<t?t:n}let o=e.toFixed(i);re(parseFloat(o)),l?.({floatValue:parseFloat(o),formattedValue:o,value:o},{source:`decrement`}),setTimeout(()=>le(ae.current?.value.length),0)};let de=e=>{let t=e.clipboardData.getData(`text`),n=B.decimalSeparator||`.`,r=(R||[`.`,`,`]).filter(e=>e!==n);if(r.some(e=>t.includes(e))){e.preventDefault();let i=t;r.forEach(e=>{i=i.split(e).join(n)});let a=ae.current;if(a){let e=a.selectionStart??0,t=a.selectionEnd??0,n=a.value,r=n.substring(0,e)+i+n.substring(t);(Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,`value`)?.set)?.call(a,r),a.dispatchEvent(new Event(`change`,{bubbles:!0}));let o=e+i.length;setTimeout(()=>le(o),0)}}B.onPaste?.(e)},fe=e=>{C?.(e),!(A||!I)&&(e.key===`ArrowUp`&&(e.preventDefault(),ue.current?.()),e.key===`ArrowDown`&&(e.preventDefault(),U.current?.()))},pe=e=>{if(w?.(e),e.key===`Backspace`){let t=ae.current;t&&t.selectionStart===0&&t.selectionStart===t.selectionEnd&&(e.preventDefault(),window.setTimeout(()=>le(0),0))}},me=e=>{let t=ne;v===`blur`&&typeof t==`number`&&(t=ut(t,p,f)),L&&typeof t==`string`&&ce(t)<15&&(t=Eh(t,f,p)),ne!==t&&re(t),y?.(e)};It(T,{increment:ue.current,decrement:U.current});let he=e=>{e?ue.current?.():U.current?.(),se.current+=1},ge=e=>{if(he(e),ie){let t=typeof N==`number`?N:N(se.current);oe.current=window.setTimeout(()=>ge(e),t)}},_e=(e,t)=>{e.preventDefault(),ae.current?.focus(),he(t),ie&&(oe.current=window.setTimeout(()=>ge(t),P))},ve=()=>{oe.current&&window.clearTimeout(oe.current),oe.current=null,se.current=0},ye=(0,G.jsxs)(`div`,{...V(`controls`),children:[(0,G.jsx)(Gc,{...V(`control`),tabIndex:-1,"aria-hidden":!0,disabled:D||typeof ne==`number`&&f!==void 0&&ne>=f,mod:{direction:`up`},onMouseDown:e=>e.preventDefault(),onPointerDown:e=>{_e(e,!0)},onPointerUp:ve,onPointerLeave:ve,children:(0,G.jsx)(mh,{direction:`up`})}),(0,G.jsx)(Gc,{...V(`control`),tabIndex:-1,"aria-hidden":!0,disabled:D||typeof ne==`number`&&p!==void 0&&ne<=p,mod:{direction:`down`},onMouseDown:e=>e.preventDefault(),onPointerDown:e=>{_e(e,!1)},onPointerUp:ve,onPointerLeave:ve,children:(0,G.jsx)(mh,{direction:`down`})})]});return(0,G.jsx)(Vu,{component:fh,allowNegative:k,className:nn(ph.root,r),size:j,inputMode:`decimal`,...B,readOnly:A,disabled:D,value:ne,getInputRef:Rt(t,ae),onValueChange:H,rightSection:h||A||!bh(ne)?g:g||ye,classNames:ee,styles:te,unstyled:o,__staticSelector:`NumberInput`,decimalScale:x?S:0,onPaste:de,onKeyDown:fe,onKeyDownCapture:pe,rightSectionPointerEvents:O??(D?`none`:void 0),rightSectionWidth:M??`var(--ni-right-section-width-${j||`sm`})`,allowLeadingZeros:F,allowedDecimalSeparators:R,onBlur:me,attributes:z,isAllowed:e=>v===`strict`?_?_(e)&&Ch(e.floatValue,p,f):Ch(e.floatValue,p,f):_?_(e):!0})});Dh.classes={...Vu.classes,...ph},Dh.displayName=`@mantine/core/NumberInput`;var Oh={duration:100,transition:`fade`};function kh(e,t){return{...Oh,...t,...e}}var Ah={tooltip:`m_1b3c8819`,arrow:`m_f898399f`};function jh({offset:e,position:t,defaultOpened:n}){let[r,i]=(0,b.useState)(n),a=(0,b.useRef)(null),{x:o,y:s,elements:c,refs:l,update:u,placement:d}=tc({placement:t,middleware:[ds({crossAxis:!0,padding:5,rootBoundary:`document`})]}),f=d.includes(`right`)?e:t.includes(`left`)?e*-1:0,p=d.includes(`bottom`)?e:t.includes(`top`)?e*-1:0,m=(0,b.useCallback)(({clientX:e,clientY:t})=>{l.setPositionReference({getBoundingClientRect(){return{width:0,height:0,x:e,y:t,left:e+f,top:t+p,right:e,bottom:t}}})},[c.reference]);return(0,b.useEffect)(()=>{if(l.floating.current){let e=a.current;e.addEventListener(`mousemove`,m);let t=$i(l.floating.current);return t.forEach(e=>{e.addEventListener(`scroll`,u)}),()=>{e.removeEventListener(`mousemove`,m),t.forEach(e=>{e.removeEventListener(`scroll`,u)})}}},[c.reference,l.floating.current,u,m,r]),{handleMouseMove:m,x:o,y:s,opened:r,setOpened:i,boundaryRef:a,floating:l.setFloating}}var Mh={refProp:`ref`,withinPortal:!0,offset:10,position:`right`,zIndex:$e(`popover`)},Nh=en((e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:it(t),"--tooltip-bg":n?An(n,e):void 0,"--tooltip-color":n?`var(--mantine-color-white)`:void 0}})),Ph=_i((e,t)=>{let n=K(`TooltipFloating`,Mh,e),{children:r,refProp:i,withinPortal:a,style:o,className:s,classNames:c,styles:l,unstyled:u,radius:d,color:f,label:p,offset:m,position:h,multiline:g,zIndex:_,disabled:v,defaultOpened:y,variant:x,vars:S,portalProps:C,attributes:w,...T}=n,E=qn(),D=jr({name:`TooltipFloating`,props:n,classes:Ah,className:s,style:o,classNames:c,styles:l,unstyled:u,attributes:w,rootSelector:`tooltip`,vars:S,varsResolver:Nh}),{handleMouseMove:O,x:k,y:A,opened:j,boundaryRef:M,floating:N,setOpened:P}=jh({offset:m,position:h,defaultOpened:y}),F=$t(r);if(!F)throw Error(`[@mantine/core] Tooltip.Floating component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported`);let I=Rt(M,Yt(F),t),L=F.props,R=e=>{L.onMouseEnter?.(e),O(e),P(!0)},z=e=>{L.onMouseLeave?.(e),P(!1)};return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(dl,{...C,withinPortal:a,children:(0,G.jsx)(q,{...T,...D(`tooltip`,{style:{...si(o,E),zIndex:_,display:!v&&j?`block`:`none`,top:(A&&Math.round(A))??``,left:(k&&Math.round(k))??``}}),variant:x,ref:N,mod:{multiline:g},children:p})}),(0,b.cloneElement)(F,{...L,[i]:I,onMouseEnter:R,onMouseLeave:z})]})});Ph.classes=Ah,Ph.displayName=`@mantine/core/TooltipFloating`;var Fh=(0,b.createContext)(!1),Ih=Fh.Provider,Lh=()=>(0,b.useContext)(Fh),Rh={openDelay:0,closeDelay:0};function zh(e){let{openDelay:t,closeDelay:n,children:r}=K(`TooltipGroup`,Rh,e);return(0,G.jsx)(Ih,{value:!0,children:(0,G.jsx)(Js,{delay:{open:t,close:n},children:r})})}zh.displayName=`@mantine/core/TooltipGroup`,zh.extend=e=>e;function Bh(e){if(e===void 0)return{shift:!0,flip:!0};let t={...e};return e.shift===void 0&&(t.shift=!0),e.flip===void 0&&(t.flip=!0),t}function Vh(e){let t=Bh(e.middlewares),n=[us(e.offset)];return t.shift&&n.push(ds(typeof t.shift==`boolean`?{padding:8}:{padding:8,...t.shift})),t.flip&&n.push(typeof t.flip==`boolean`?ps():ps(t.flip)),n.push(_s({element:e.arrowRef,padding:e.arrowOffset})),t.inline?n.push(typeof t.inline==`boolean`?gs():gs(t.inline)):e.inline&&n.push(gs()),n}function Hh(e){let[t,n]=(0,b.useState)(e.defaultOpened),r=typeof e.opened==`boolean`?e.opened:t,i=Lh(),a=Pt(),o=(0,b.useCallback)(e=>{n(e),e&&g(a)},[a]),{x:s,y:c,context:l,refs:u,placement:d,middlewareData:{arrow:{x:f,y:p}={}}}=tc({strategy:e.strategy,placement:e.position,open:r,onOpenChange:o,middleware:Vh(e),whileElementsMounted:qo}),{delay:m,currentId:h,setCurrentId:g}=Ys(l,{id:a}),{getReferenceProps:_,getFloatingProps:v}=ac([Ws(l,{enabled:e.events?.hover,delay:i?m:{open:e.openDelay,close:e.closeDelay},mouseOnly:!e.events?.touch}),rc(l,{enabled:e.events?.focus,visibleOnly:!0}),sc(l,{role:`tooltip`}),$s(l,{enabled:e.opened===void 0})]);bt(()=>{e.onPositionChange?.(d)},[d]);let y=r&&h&&h!==a;return{x:s,y:c,arrowX:f,arrowY:p,reference:u.setReference,floating:u.setFloating,getFloatingProps:v,getReferenceProps:_,isGroupPhase:y,opened:r,placement:d}}var Uh={position:`top`,refProp:`ref`,withinPortal:!0,arrowSize:4,arrowOffset:5,arrowRadius:0,arrowPosition:`side`,offset:5,transitionProps:{duration:100,transition:`fade`},events:{hover:!0,focus:!1,touch:!1},zIndex:$e(`popover`),positionDependencies:[],middlewares:{flip:!0,shift:!0,inline:!1}},Wh=en((e,{radius:t,color:n,variant:r,autoContrast:i})=>{let a=e.variantColorResolver({theme:e,color:n||e.primaryColor,autoContrast:i,variant:r||`filled`});return{tooltip:{"--tooltip-radius":t===void 0?void 0:it(t),"--tooltip-bg":n?a.background:void 0,"--tooltip-color":n?a.color:void 0}}}),Gh=_i((e,t)=>{let n=K(`Tooltip`,Uh,e),{children:r,position:i,refProp:a,label:o,openDelay:s,closeDelay:c,onPositionChange:l,opened:u,defaultOpened:d,withinPortal:f,radius:p,color:m,classNames:h,styles:g,unstyled:_,style:v,className:y,withArrow:x,arrowSize:S,arrowOffset:C,arrowRadius:w,arrowPosition:T,offset:E,transitionProps:D,multiline:O,events:k,zIndex:A,disabled:j,positionDependencies:M,onClick:N,onMouseEnter:P,onMouseLeave:F,inline:I,variant:L,keepMounted:R,vars:z,portalProps:B,mod:V,floatingStrategy:ee,middlewares:te,autoContrast:ne,attributes:re,target:ie,...ae}=K(`Tooltip`,Uh,n),{dir:oe}=bi(),se=(0,b.useRef)(null),H=Hh({position:nl(oe,i),closeDelay:c,openDelay:s,onPositionChange:l,opened:u,defaultOpened:d,events:k,arrowRef:se,arrowOffset:C,offset:typeof E==`number`?E+(x?S/2:0):E,positionDependencies:[...M,ie??r],inline:I,strategy:ee,middlewares:te});(0,b.useEffect)(()=>{let e=ie instanceof HTMLElement?ie:typeof ie==`string`?document.querySelector(ie):ie?.current||null;e&&H.reference(e)},[ie,H]);let ce=jr({name:`Tooltip`,props:n,classes:Ah,className:y,style:v,classNames:h,styles:g,unstyled:_,attributes:re,rootSelector:`tooltip`,vars:z,varsResolver:Wh}),le=$t(r);if(!ie&&!le)throw Error(`[@mantine/core] Tooltip component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported`);if(ie){let e=kh(D,{duration:100,transition:`fade`});return(0,G.jsx)(G.Fragment,{children:(0,G.jsx)(dl,{...B,withinPortal:f,children:(0,G.jsx)(_l,{...e,keepMounted:R,mounted:!j&&!!H.opened,duration:H.isGroupPhase?10:e.duration,children:e=>(0,G.jsxs)(q,{...ae,"data-fixed":ee===`fixed`||void 0,variant:L,mod:[{multiline:O},V],...H.getFloatingProps({ref:H.floating,className:ce(`tooltip`).className,style:{...ce(`tooltip`).style,...e,zIndex:A,top:H.y??0,left:H.x??0}}),children:[o,(0,G.jsx)(tl,{ref:se,arrowX:H.arrowX,arrowY:H.arrowY,visible:x,position:H.placement,arrowSize:S,arrowOffset:C,arrowRadius:w,arrowPosition:T,...ce(`arrow`)})]})})})})}let ue=le.props,U=Rt(H.reference,Yt(le),t),de=kh(D,{duration:100,transition:`fade`});return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(dl,{...B,withinPortal:f,children:(0,G.jsx)(_l,{...de,keepMounted:R,mounted:!j&&!!H.opened,duration:H.isGroupPhase?10:de.duration,children:e=>(0,G.jsxs)(q,{...ae,"data-fixed":ee===`fixed`||void 0,variant:L,mod:[{multiline:O},V],...H.getFloatingProps({ref:H.floating,className:ce(`tooltip`).className,style:{...ce(`tooltip`).style,...e,zIndex:A,top:H.y??0,left:H.x??0}}),children:[o,(0,G.jsx)(tl,{ref:se,arrowX:H.arrowX,arrowY:H.arrowY,visible:x,position:H.placement,arrowSize:S,arrowOffset:C,arrowRadius:w,arrowPosition:T,...ce(`arrow`)})]})})}),(0,b.cloneElement)(le,H.getReferenceProps({onClick:N,onMouseEnter:P,onMouseLeave:F,onMouseMove:n.onMouseMove,onPointerDown:n.onPointerDown,onPointerEnter:n.onPointerEnter,...ue,className:nn(y,ue.className),[a]:U}))]})});Gh.classes=Ah,Gh.displayName=`@mantine/core/Tooltip`,Gh.Floating=Ph,Gh.Group=zh;var Kh={withCheckIcon:!0,allowDeselect:!0,checkIconPosition:`left`,openOnFocus:!0},qh=_i((e,t)=>{let n=K(`Select`,Kh,e),{classNames:r,styles:i,unstyled:a,vars:o,dropdownOpened:s,defaultDropdownOpened:c,onDropdownClose:l,onDropdownOpen:u,onFocus:d,onBlur:f,onClick:p,onChange:m,data:h,value:g,defaultValue:_,selectFirstOptionOnChange:v,selectFirstOptionOnDropdownOpen:y,onOptionSubmit:x,comboboxProps:S,readOnly:C,disabled:w,filter:T,limit:E,withScrollArea:D,maxDropdownHeight:O,size:k,searchable:A,rightSection:j,checkIconPosition:M,withCheckIcon:N,withAlignedLabels:P,nothingFoundMessage:F,name:I,form:L,searchValue:R,defaultSearchValue:z,onSearchChange:B,allowDeselect:V,error:ee,rightSectionPointerEvents:te,id:ne,clearable:re,clearButtonProps:ie,hiddenInputProps:ae,renderOption:oe,onClear:se,autoComplete:H,scrollAreaProps:ce,__defaultRightSection:le,__clearSection:ue,__clearable:U,chevronColor:de,autoSelectOnBlur:fe,openOnFocus:pe,attributes:me,...he}=n,ge=(0,b.useMemo)(()=>nd(h),[h]),_e=(0,b.useRef)({}),ve=(0,b.useMemo)(()=>rd(ge),[ge]),ye=Pt(ne),[be,xe,Se]=Vt({value:g,defaultValue:_,finalValue:null,onChange:m}),Ce=typeof be==`string`?be in ve?ve[be]:_e.current[be]:void 0,we=Wt(Ce),[Te,Ee,De]=Vt({value:R,defaultValue:z,finalValue:Ce?Ce.label:``,onChange:B}),Oe=jd({opened:s,defaultOpened:c,onDropdownOpen:()=>{u?.(),y?Oe.selectFirstOption():Oe.updateSelectedOptionIndex(`active`,{scrollIntoView:!0})},onDropdownClose:()=>{l?.(),setTimeout(Oe.resetSelectedOption,0)}}),ke=e=>{Ee(e),Oe.resetSelectedOption()},{resolvedClassNames:Ae,resolvedStyles:je}=mr({props:n,styles:i,classNames:r});(0,b.useEffect)(()=>{v&&Oe.selectFirstOption()},[v,Te]),(0,b.useEffect)(()=>{g===null&&ke(``),typeof g==`string`&&Ce&&(we?.value!==Ce.value||we?.label!==Ce.label)&&ke(Ce.label)},[g,Ce]),(0,b.useEffect)(()=>{!Se&&!De&&ke(typeof be==`string`?be in ve?ve[be]?.label:_e.current[be]?.label||``:``)},[ve,be]),(0,b.useEffect)(()=>{be&&be in ve&&(_e.current[be]=ve[be])},[ve,be]);let Me=(0,G.jsx)(Pd.ClearButton,{...ie,onClear:()=>{xe(null,null),ke(``),se?.()}}),Ne=re&&!!be&&!w&&!C;return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(Pd,{store:Oe,__staticSelector:`Select`,classNames:Ae,styles:je,unstyled:a,readOnly:C,size:k,attributes:me,keepMounted:fe,onOptionSubmit:e=>{x?.(e);let t=V&&ve[e].value===be?null:ve[e],n=t?t.value:null;n!==be&&xe(n,t),!Se&&ke(typeof n==`string`&&t?.label||``),Oe.closeDropdown()},...S,children:[(0,G.jsx)(Pd.Target,{targetType:A?`input`:`button`,autoComplete:H,children:(0,G.jsx)(Vu,{id:ye,ref:t,__defaultRightSection:(0,G.jsx)(Pd.Chevron,{size:k,error:ee,unstyled:a,color:de}),__clearSection:Me,__clearable:Ne,rightSection:j,rightSectionPointerEvents:te||`none`,...he,size:k,__staticSelector:`Select`,disabled:w,readOnly:C||!A,value:Te,onChange:e=>{ke(e.currentTarget.value),Oe.openDropdown(),v&&Oe.selectFirstOption()},onFocus:e=>{pe&&A&&Oe.openDropdown(),d?.(e)},onBlur:e=>{fe&&Oe.clickSelectedOption(),A&&Oe.closeDropdown();let t=typeof be==`string`&&(be in ve?ve[be]:_e.current[be]);ke(t&&t.label||``),f?.(e)},onClick:e=>{A?Oe.openDropdown():Oe.toggleDropdown(),p?.(e)},classNames:Ae,styles:je,unstyled:a,pointer:!A,error:ee,attributes:me})}),(0,G.jsx)(ff,{data:ge,hidden:C||w,filter:T,search:Te,limit:E,hiddenWhenEmpty:!F,withScrollArea:D,maxDropdownHeight:O,filterOptions:!!A&&Ce?.label!==Te,value:be,checkIconPosition:M,withCheckIcon:N,withAlignedLabels:P,nothingFoundMessage:F,unstyled:a,labelId:he.label?`${ye}-label`:void 0,"aria-label":he.label?void 0:he[`aria-label`],renderOption:oe,scrollAreaProps:ce})]}),(0,G.jsx)(Pd.HiddenInput,{value:be,name:I,form:L,disabled:w,...ae})]})});qh.classes={...Vu.classes,...Pd.classes},qh.displayName=`@mantine/core/Select`;var[Jh,Yh]=Ge(`SliderProvider was not found in tree`),Xh={root:`m_dd36362e`,label:`m_c9357328`,thumb:`m_c9a9a60a`,trackContainer:`m_a8645c2`,track:`m_c9ade57f`,bar:`m_38aeed47`,markWrapper:`m_b7b0423a`,mark:`m_dd33bc19`,markLabel:`m_68c77a5b`},Zh=(0,b.forwardRef)(({size:e,disabled:t,variant:n,color:r,thumbSize:i,radius:a,...o},s)=>{let{getStyles:c}=Yh();return(0,G.jsx)(q,{tabIndex:-1,variant:n,size:e,ref:s,...c(`root`),...o})});Zh.displayName=`@mantine/core/SliderRoot`;var Qh=(0,b.forwardRef)(({max:e,min:t,value:n,position:r,label:i,dragging:a,onMouseDown:o,onKeyDownCapture:s,labelTransitionProps:c,labelAlwaysOn:l,thumbLabel:u,onFocus:d,onBlur:f,showLabelOnHover:p,isHovered:m,children:h=null,disabled:g},_)=>{let{getStyles:v}=Yh(),[y,x]=(0,b.useState)(!1),S=l||a||y||p&&m;return(0,G.jsxs)(q,{tabIndex:0,role:`slider`,"aria-label":u,"aria-valuemax":e,"aria-valuemin":t,"aria-valuenow":n,ref:_,__vars:{"--slider-thumb-offset":`${r}%`},...v(`thumb`,{focusable:!0}),mod:{dragging:a,disabled:g},onFocus:e=>{x(!0),typeof d==`function`&&d(e)},onBlur:e=>{x(!1),typeof f==`function`&&f(e)},onTouchStart:o,onMouseDown:o,onKeyDownCapture:s,onClick:e=>e.stopPropagation(),children:[h,(0,G.jsx)(_l,{mounted:i!=null&&!!S,transition:`fade`,duration:0,...c,children:e=>(0,G.jsx)(`div`,{...v(`label`,{style:e}),children:i})})]})});Qh.displayName=`@mantine/core/SliderThumb`;function $h({value:e,min:t,max:n}){let r=(e-t)/(n-t)*100;return Math.min(Math.max(r,0),100)}function eg({mark:e,offset:t,value:n,inverted:r=!1}){return r?typeof t==`number`&&e.value<=t||e.value>=n:typeof t==`number`?e.value>=t&&e.value<=n:e.value<=n}function tg({marks:e,min:t,max:n,disabled:r,value:i,offset:a,inverted:o}){let{getStyles:s}=Yh();return e?(0,G.jsx)(`div`,{children:e.map((e,c)=>(0,b.createElement)(q,{...s(`markWrapper`),__vars:{"--mark-offset":`${$h({value:e.value,min:t,max:n})}%`},key:c},(0,G.jsx)(q,{...s(`mark`),mod:{filled:eg({mark:e,value:i,offset:a,inverted:o}),disabled:r}}),e.label&&(0,G.jsx)(`div`,{...s(`markLabel`),children:e.label})))}):null}tg.displayName=`@mantine/core/SliderMarks`;function ng({filled:e,children:t,offset:n,disabled:r,marksOffset:i,inverted:a,containerProps:o,...s}){let{getStyles:c}=Yh();return(0,G.jsx)(q,{...c(`trackContainer`),mod:{disabled:r},...o,children:(0,G.jsxs)(q,{...c(`track`),mod:{inverted:a,disabled:r},children:[(0,G.jsx)(q,{mod:{inverted:a,disabled:r},__vars:{"--slider-bar-width":`calc(${e}% + 2 * var(--slider-size))`,"--slider-bar-offset":`calc(${n}% - var(--slider-size))`},...c(`bar`)}),t,(0,G.jsx)(tg,{...s,offset:i,disabled:r,inverted:a})]})})}ng.displayName=`@mantine/core/SliderTrack`;function rg({value:e,containerWidth:t,min:n,max:r,step:i,precision:a}){let o=(t?Math.min(Math.max(e,0),t)/t:e)*(r-n),s=(o===0?0:Math.round(o/i)*i)+n,c=Math.max(s,n);return a===void 0?c:Number(c.toFixed(a))}function ig(e,t){return parseFloat(e.toFixed(t))}function ag(e){if(!e)return 0;let t=e.toString().split(`.`);return t.length>1?t[1].length:0}function og(e,t){let n=[...t].sort((e,t)=>e.value-t.value).find(t=>t.value>e);return n?n.value:e}function sg(e,t){let n=[...t].sort((e,t)=>t.value-e.value).find(t=>t.value<e);return n?n.value:e}function cg(e){let t=[...e].sort((e,t)=>e.value-t.value);return t.length>0?t[0].value:0}function lg(e){let t=[...e].sort((e,t)=>e.value-t.value);return t.length>0?t[t.length-1].value:100}var ug={radius:`xl`,min:0,max:100,step:1,marks:[],label:e=>e,labelTransitionProps:{transition:`fade`,duration:0},thumbLabel:``,showLabelOnHover:!0,scale:e=>e,size:`md`},dg=en((e,{size:t,color:n,thumbSize:r,radius:i})=>({root:{"--slider-size":nt(t,`slider-size`),"--slider-color":n?An(n,e):void 0,"--slider-radius":i===void 0?void 0:it(i),"--slider-thumb-size":r===void 0?`calc(var(--slider-size) * 2)`:W(r)}})),fg=_i((e,t)=>{let n=K(`Slider`,ug,e),{classNames:r,styles:i,value:a,onChange:o,onChangeEnd:s,size:c,min:l,max:u,domain:d,step:f,precision:p,defaultValue:m,name:h,marks:g,label:_,labelTransitionProps:v,labelAlwaysOn:y,thumbLabel:x,showLabelOnHover:S,thumbChildren:C,disabled:w,unstyled:T,scale:E,inverted:D,className:O,style:k,vars:A,hiddenInputProps:j,restrictToMarks:M,thumbProps:N,attributes:P,...F}=n,I=jr({name:`Slider`,props:n,classes:Xh,classNames:r,className:O,styles:i,style:k,attributes:P,vars:A,varsResolver:dg,unstyled:T}),{dir:L}=bi(),[R,z]=(0,b.useState)(!1),[B,V]=Vt({value:typeof a==`number`?ut(a,l,u):a,defaultValue:typeof m==`number`?ut(m,l,u):m,finalValue:ut(0,l,u),onChange:o}),ee=(0,b.useRef)(B),te=(0,b.useRef)(s);(0,b.useEffect)(()=>{te.current=s},[s]);let ne=(0,b.useRef)(null),re=(0,b.useRef)(null),[ie,ae]=d||[l,u],oe=$h({value:B,min:ie,max:ae}),se=E(B),H=typeof _==`function`?_(se):_,ce=p??ag(f),{ref:le,active:ue}=Bt((0,b.useCallback)(({x:e})=>{if(!w){let t=ut(rg({value:e,min:ie,max:ae,step:f,precision:ce}),l,u);V(M&&g?.length?Jt(t,g.map(e=>e.value)):t),ee.current=t}},[w,l,u,ie,ae,f,ce,V,g,M]),{onScrubEnd:(0,b.useCallback)(()=>{if(!w&&te.current){let e=M&&g?.length?Jt(ee.current,g.map(e=>e.value)):ee.current;te.current(e)}},[w,g,M])},L),U=(0,b.useCallback)(e=>{!w&&te.current&&te.current(e)},[w]),de=e=>{if(!w)switch(e.key){case`ArrowUp`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=og(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(B+f,l),u),ce);V(t),U(t);break}case`ArrowRight`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=L===`rtl`?sg(B,g):og(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(L===`rtl`?B-f:B+f,l),u),ce);V(t),U(t);break}case`ArrowDown`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=sg(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(B-f,l),u),ce);V(t),U(t);break}case`ArrowLeft`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=L===`rtl`?og(B,g):sg(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(L===`rtl`?B+f:B-f,l),u),ce);V(t),U(t);break}case`Home`:if(e.preventDefault(),re.current?.focus(),M&&g){V(cg(g)),U(cg(g));break}V(l),U(l);break;case`End`:if(e.preventDefault(),re.current?.focus(),M&&g){V(lg(g)),U(lg(g));break}V(u),U(u);break}};return(0,G.jsx)(Jh,{value:{getStyles:I},children:(0,G.jsxs)(Zh,{...F,ref:Rt(t,ne),onKeyDownCapture:de,onMouseDownCapture:()=>ne.current?.focus(),size:c,disabled:w,children:[(0,G.jsx)(ng,{inverted:D,offset:0,filled:oe,marks:g,min:ie,max:ae,value:se,disabled:w,containerProps:{ref:le,onMouseEnter:S?()=>z(!0):void 0,onMouseLeave:S?()=>z(!1):void 0},children:(0,G.jsx)(Qh,{max:ae,min:ie,value:se,position:oe,dragging:ue,label:H,ref:re,labelTransitionProps:v,labelAlwaysOn:y,thumbLabel:x,showLabelOnHover:S,isHovered:R,disabled:w,...N,children:C})}),(0,G.jsx)(`input`,{type:`hidden`,name:h,value:se,...j})]})})});fg.classes=Xh,fg.displayName=`@mantine/core/Slider`;var pg={root:`m_6d731127`},mg={gap:`md`,align:`stretch`,justify:`flex-start`},hg=en((e,{gap:t,align:n,justify:r})=>({root:{"--stack-gap":rt(t),"--stack-align":n,"--stack-justify":r}})),gg=_i((e,t)=>{let n=K(`Stack`,mg,e),{classNames:r,className:i,style:a,styles:o,unstyled:s,vars:c,align:l,justify:u,gap:d,variant:f,attributes:p,...m}=n;return(0,G.jsx)(q,{ref:t,...jr({name:`Stack`,props:n,classes:pg,className:i,style:a,classNames:r,styles:o,unstyled:s,attributes:p,vars:c,varsResolver:hg})(`root`),variant:f,...m})});gg.classes=pg,gg.displayName=`@mantine/core/Stack`;var _g=_i((e,t)=>(0,G.jsx)(Vu,{component:`input`,ref:t,...K(`TextInput`,null,e),__staticSelector:`TextInput`}));_g.classes=Vu.classes,_g.displayName=`@mantine/core/TextInput`;var vg={outline:{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`},filled:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`currentColor`,stroke:`none`}},yg=(e,t,n,r)=>{let i=(0,b.forwardRef)(({color:n=`currentColor`,size:i=24,stroke:a=2,title:o,className:s,children:c,...l},u)=>(0,b.createElement)(`svg`,{ref:u,...vg[e],width:i,height:i,className:[`tabler-icon`,`tabler-icon-${t}`,s].join(` `),...e===`filled`?{fill:n}:{strokeWidth:a,stroke:n},...l},[o&&(0,b.createElement)(`title`,{key:`svg-title`},o),...r.map(([e,t])=>(0,b.createElement)(e,t)),...Array.isArray(c)?c:[c]]));return i.displayName=`${n}`,i},bg=yg(`outline`,`chevron-down`,`ChevronDown`,[[`path`,{d:`M6 9l6 6l6 -6`,key:`svg-0`}]]),xg=yg(`outline`,`chevron-up`,`ChevronUp`,[[`path`,{d:`M6 15l6 -6l6 6`,key:`svg-0`}]]),Sg=yg(`outline`,`refresh`,`Refresh`,[[`path`,{d:`M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4`,key:`svg-0`}],[`path`,{d:`M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4`,key:`svg-1`}]]),Cg=yg(`outline`,`x`,`X`,[[`path`,{d:`M18 6l-12 12`,key:`svg-0`}],[`path`,{d:`M6 6l12 12`,key:`svg-1`}]]),wg=d(),Tg=`0.8.1`,Eg=[{login:`ttktjmt`,html_url:`https://github.com/ttktjmt`},{login:`claude`,html_url:`https://github.com/claude`},{login:`Axellwppr`,html_url:`https://github.com/Axellwppr`},{login:`julien-blanchon`,html_url:`https://github.com/julien-blanchon`},{login:`unmoyai`,html_url:`https://github.com/unmoyai`},{login:`brentyi`,html_url:`https://github.com/brentyi`},{login:`CharlieLeee`,html_url:`https://github.com/CharlieLeee`}],Dg={move:`touchmove`,end:`touchend`},Og={move:`mousemove`,end:`mouseup`};function kg(e){return e.type===`touchmove`}function Ag(e){return e.type===`mousemove`}var jg=b.createContext(null);function Mg({children:e,width:t,visible:n=!0,onVisibleChange:r,hiddenButtonTooltip:i}){let a=b.useRef(null),[o,{toggle:s}]=Ut(!0),[c,l]=b.useState(800),u=b.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),d=b.useRef({}),f=(e,t,n)=>Math.abs(e+t/2)<Math.abs(e-n+t/2)?e:e-n;function p(e,t){let n=a.current;if(n===null)return[e,t];let r=n.parentElement;if(r===null)return[e,t];let i=e,o=t;return i=Math.min(i,r.clientWidth-n.clientWidth-15),i=Math.max(i,15),o=Math.min(o,r.clientHeight-n.clientHeight-15),o=Math.max(o,15),n.style.top=`${o.toString()}px`,n.style.left=`${i.toString()}px`,[f(i,n.clientWidth,r.clientWidth),f(o,n.clientHeight,r.clientHeight)]}b.useEffect(()=>{let e=a.current;if(e===null)return;let t=e.parentElement;if(t===null)return;let n=new ResizeObserver(()=>{d.current.x===void 0&&(d.current.x=f(e.offsetLeft,e.clientWidth,t.clientWidth)),d.current.y===void 0&&(d.current.y=f(e.offsetTop,e.clientHeight,t.clientHeight));let n=t.clientHeight-30;c!==n&&l(n);let r=d.current.x,i=d.current.y;for(;r<0;)r+=t.clientWidth;for(;i<0;)i+=t.clientHeight;p(r,i)});return n.observe(e),n.observe(t),()=>{n.disconnect()}});let m=e=>{let t=u.current,n=a.current;if(!n)return;e.type==`touchstart`?(e=e,t.startClientX=e.touches[0].clientX,t.startClientY=e.touches[0].clientY):(e=e,t.startClientX=e.clientX,t.startClientY=e.clientY),t.startPosX=n.offsetLeft,t.startPosY=n.offsetTop;let r=e.type==`touchstart`?Dg:Og;function i(e){let n=0,r=0;if(kg(e)?(e=e,n=e.touches[0].clientX-t.startClientX,r=e.touches[0].clientY-t.startClientY):Ag(e)&&(e=e,n=e.clientX-t.startClientX,r=e.clientY-t.startClientY),Math.abs(n)<=3&&Math.abs(r)<=3)return;t.dragging=!0;let i=t.startPosX+n,a=t.startPosY+r;[d.current.x,d.current.y]=p(i,a)}window.addEventListener(r.move,i),window.addEventListener(r.end,()=>{e.type==`touchstart`&&(t.dragging=!1),window.removeEventListener(r.move,i)},{once:!0})};if(!n){let e=(0,G.jsx)(q,{component:`button`,"aria-label":i??`Show controls`,onClick:()=>r?.(!0),style:{width:`0.85rem`,height:`0.85rem`,minWidth:`0.85rem`,minHeight:`0.85rem`,display:`block`,padding:0,border:`none`,borderRadius:`9999px`,background:`rgba(255, 255, 255, 0.82)`,boxShadow:`0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)`,cursor:`pointer`}});return(0,G.jsx)(q,{style:{zIndex:10,position:`absolute`,top:`1em`,right:`1em`},children:i?(0,G.jsx)(Gh,{label:i,children:(0,G.jsx)(q,{children:e})}):e})}return(0,G.jsx)(jg.Provider,{value:{wrapperRef:a,expanded:o,width:t,maxHeight:c,toggleExpanded:s,dragHandler:m,dragInfo:u},children:(0,G.jsx)(Xc,{radius:`xs`,shadow:`0.1em 0 1em 0 rgba(0,0,0,0.1)`,style:{boxSizing:`border-box`,width:t,zIndex:10,position:`absolute`,top:`1em`,right:`1em`,margin:0,"& .expandIcon":{transform:`rotate(0)`},overflow:`hidden`},ref:a,children:e})})}Mg.Handle=function({children:e}){let t=b.useContext(jg);return(0,G.jsx)(G.Fragment,{children:(0,G.jsx)(q,{style:{borderRadius:`0.2em 0.2em 0 0`,lineHeight:`1.5em`,cursor:`pointer`,position:`relative`,fontWeight:400,userSelect:`none`,display:`flex`,alignItems:`center`,padding:`0 0.75em`,height:`2.75em`},onClick:()=>{let e=t.dragInfo.current;if(e.dragging){e.dragging=!1;return}t.toggleExpanded()},onTouchStart:e=>{t.dragHandler(e)},onMouseDown:e=>{t.dragHandler(e)},children:e})})},Mg.Contents=function({children:e}){let t=b.useContext(jg);return(0,G.jsxs)(ki,{in:t.expanded,children:[(0,G.jsx)(hp,{mx:`xs`}),(0,G.jsx)(Vc.Autosize,{mah:t.maxHeight,children:(0,G.jsx)(q,{style:{width:t.width},children:e})})]})},Mg.HideWhenCollapsed=function({children:e}){return b.useContext(jg)?.expanded??!0?e:null},Mg.HideWhenExpanded=function({children:e}){return b.useContext(jg)?.expanded??!0?null:e};function Ng({id:e,label:t,children:n}){return(0,G.jsx)(q,{pb:`0.5em`,px:`xs`,children:(0,G.jsxs)(Wu,{align:`center`,children:[(0,G.jsx)(q,{pr:`xs`,style:{width:`7.25em`,flexShrink:0,position:`relative`},children:(0,G.jsx)(Zu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`100%`,boxSizing:`content-box`},children:(0,G.jsx)(`label`,{htmlFor:e,children:t})})}),(0,G.jsx)(q,{style:{flexGrow:1},children:n})]})})}function Pg({label:e,expandByDefault:t=!0,children:n}){let[r,{toggle:i}]=Ut(t);return(0,G.jsxs)(Xc,{withBorder:!0,style:{borderWidth:`1px`,position:`relative`,marginLeft:`var(--mantine-spacing-xs)`,marginRight:`var(--mantine-spacing-xs)`,marginTop:`var(--mantine-spacing-xs)`,marginBottom:`var(--mantine-spacing-xs)`,paddingBottom:`calc(var(--mantine-spacing-xs) - 0.5em)`},children:[(0,G.jsxs)(Xc,{onClick:i,style:{fontSize:`0.875em`,position:`absolute`,padding:`0 0.375em`,top:0,left:`0.375em`,transform:`translateY(-50%)`,userSelect:`none`,fontWeight:500,cursor:`pointer`,display:`flex`,alignItems:`center`},children:[e,(0,G.jsx)(r?xg:bg,{style:{width:`0.9em`,height:`0.9em`,strokeWidth:3,top:`0.1em`,position:`relative`,marginLeft:`0.25em`,marginRight:`-0.1em`,opacity:.5}})]}),(0,G.jsx)(ki,{in:r,children:(0,G.jsx)(q,{pt:`1em`,children:n})}),(0,G.jsx)(ki,{in:!r,children:(0,G.jsx)(q,{p:`xs`})})]})}var Fg={fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`4.5em`,flexShrink:0},Ig={root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}},Lg={flex:1,minWidth:0,height:`1.75em`,fontSize:`0.8em`,fontFamily:`inherit`,border:`1px solid var(--mantine-color-default-border)`,borderRadius:`var(--mantine-radius-sm)`,background:`var(--mantine-color-default)`,color:`var(--mantine-color-text)`,textAlign:`right`,padding:`0 0.4em`,outline:`none`,cursor:`ns-resize`,touchAction:`none`};function Rg({axis:e,value:t,min:n=-1/0,max:r=1/0,step:i,onChange:a}){let o=(0,b.useRef)(null),s=(0,b.useRef)(null);(0,b.useEffect)(()=>{let e=o.current;e&&document.activeElement!==e&&(e.value=t.toFixed(2))},[t]);let c=e=>Math.max(n,Math.min(r,parseFloat((Math.round(e/i)*i).toFixed(10))));return(0,G.jsxs)(q,{style:{display:`flex`,alignItems:`center`,gap:`0.25em`,flex:1},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,letterSpacing:`-0.75px`,flexShrink:0},children:e}),(0,G.jsx)(`input`,{ref:o,size:1,defaultValue:t.toFixed(2),onPointerDown:e=>{e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),s.current={startY:e.clientY,startValue:t,moved:!1}},onPointerMove:e=>{if(!s.current||!(e.buttons&1))return;let t=s.current.startY-e.clientY;if(Math.abs(t)>3&&(s.current.moved=!0),!s.current.moved)return;let n=c(s.current.startValue+t*i);a(n),o.current&&(o.current.value=n.toFixed(2))},onPointerUp:()=>{if(s.current&&!s.current.moved){let e=o.current;e&&(e.focus(),e.select())}s.current=null},onBlur:e=>{let n=parseFloat(e.target.value);isNaN(n)||a(c(n)),e.target.value=t.toFixed(2)},onKeyDown:e=>{e.key===`Enter`&&e.currentTarget.blur(),e.key===`Escape`&&(o.current&&(o.current.value=t.toFixed(2)),o.current?.blur())},onFocus:e=>e.currentTarget.style.outline=`2px solid var(--mantine-color-blue-5)`,onBlurCapture:e=>e.currentTarget.style.outline=`none`,style:Lg})]})}function zg({label:e,x:t,y:n,z:r,step:i,xLabel:a=`X`,yLabel:o=`Y`,zLabel:s=`Z`,onX:c,onY:l,onZ:u}){return(0,G.jsxs)(q,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:Fg,children:e}),(0,G.jsx)(Rg,{axis:a,value:t,step:i,onChange:c}),(0,G.jsx)(Rg,{axis:o,value:n,step:i,onChange:l}),(0,G.jsx)(Rg,{axis:s,value:r,step:i,onChange:u})]})}function Bg({scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o,onCalibrate:s}){let[c,l]=(0,b.useState)(e),[u,d]=(0,b.useState)(t),[f,p]=(0,b.useState)(n),[m,h]=(0,b.useState)(r),[g,_]=(0,b.useState)(i),[v,y]=(0,b.useState)(a),[x,S]=(0,b.useState)(o);(0,b.useEffect)(()=>{l(e)},[e]),(0,b.useEffect)(()=>{d(t)},[t]),(0,b.useEffect)(()=>{p(n)},[n]),(0,b.useEffect)(()=>{h(r)},[r]),(0,b.useEffect)(()=>{_(i)},[i]),(0,b.useEffect)(()=>{y(a)},[a]),(0,b.useEffect)(()=>{S(o)},[o]);let C=(e,t,n,r,i,a,o)=>s(e,t,n,r,i,a,o);return(0,G.jsxs)(Pg,{label:`Control`,expandByDefault:!0,children:[(0,G.jsxs)(q,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:Fg,children:`Scale`}),(0,G.jsx)(q,{style:{flex:1},children:(0,G.jsx)(fg,{value:c,onChange:e=>{l(e),C(e,u,f,m,g,v,x)},min:.1,max:5,step:.05,size:`xs`,label:e=>e.toFixed(2),styles:Ig})})]}),(0,G.jsx)(zg,{label:`Position`,x:u,y:f,z:m,step:.05,onX:e=>{d(e),C(c,e,f,m,g,v,x)},onY:e=>{p(e),C(c,u,e,m,g,v,x)},onZ:e=>{h(e),C(c,u,f,e,g,v,x)}}),(0,G.jsx)(zg,{label:`Rotation`,x:g,y:v,z:x,step:.5,xLabel:`R`,yLabel:`P`,zLabel:`Y`,onX:e=>{_(e),C(c,u,f,m,e,v,x)},onY:e=>{y(e),C(c,u,f,m,g,e,x)},onZ:e=>{S(e),C(c,u,f,m,g,v,e)}})]})}function Vg(e){return e instanceof HTMLElement?e.isContentEditable?!0:e.closest(`input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]`)!==null:!1}function Hg(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Ug({command:e,value:t,onChange:n,disabled:r,enabledWhenValue:i}){let a=e.enabledWhen!==void 0&&(i??0)<.5,o=r||a;return(0,G.jsxs)(q,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`50%`,flexShrink:0},children:e.label}),(0,G.jsx)(q,{style:{width:`50%`},children:(0,G.jsx)(fg,{value:t,onChange:t=>n(e.id,t),min:e.min,max:e.max,step:e.step,size:`xs`,disabled:o,styles:{root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}}})})]})}function Wg({command:e,value:t,onChange:n,disabled:r}){return(0,G.jsx)(q,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(af,{label:e.label,checked:t>=.5,onChange:t=>n(e.id,+!!t.currentTarget.checked),size:`xs`,disabled:r})})}function Gg(e){let{visible:t,onVisibleChange:n,projects:r,projectValue:i,projectLabel:a,onProjectChange:o,scenes:s,sceneValue:c,onSceneChange:l,splats:u,splatSection:d=!1,splatValue:f,onSplatChange:p,splatConfig:m,onCalibrateSplat:h,onSplatUrlLoad:g,policies:_,policyValue:v,onPolicyChange:y,motions:x,motionValue:S,onMotionChange:C,showReferenceMotion:w,onShowReferenceMotionChange:T,commandsEnabled:E=!1,commands:D,commandValues:O,onCommandChange:k,onReset:A}=e,[j,{open:M,close:N}]=Ut(!1),[P,F]=(0,b.useState)(``),[I,L]=(0,b.useState)(null),[R,z]=(0,b.useState)(!1),B=(0,b.useCallback)(async e=>{if(e.key!==`Enter`||!g)return;let t=P.trim();if(!u.some(e=>e.label===t||e.value===t)){if(!t.toLowerCase().endsWith(`.spz`)){L(`URL must end with .spz`);return}await g(t)?(L(null),z(!0)):L(`File not found at the specified URL`)}},[g,P,u]),V=Array.from(new Set(D.map(e=>e.group))),ee=(0,b.useCallback)(()=>{A?.()},[A]);(0,b.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.repeat||e.altKey||e.ctrlKey||e.metaKey)return;let r=e.key.toLowerCase();r!==`c`&&r!==`r`||Vg(e.target instanceof Element?e.target:document.activeElement)||(e.preventDefault(),r===`c`?n(!t):ee())};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,n,ee]);let te=e=>D.filter(t=>t.group===e&&(t.type===`slider`||t.type===`checkbox`));return!r.length&&!s.length&&!_.length?null:(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Cm,{opened:j,onClose:N,size:`lg`,title:null,centered:!0,styles:{body:{textAlign:`center`}},children:(0,G.jsxs)(gg,{gap:`md`,align:`center`,children:[(0,G.jsx)(vp,{src:`/logo.svg`,style:{width:`8em`,height:`auto`}}),(0,G.jsx)(Zu,{size:`xl`,fw:700,children:`powered by mjswan`}),(0,G.jsxs)(Zu,{size:`sm`,c:`dimmed`,children:[`version `,Tg]}),(0,G.jsx)(Zu,{size:`sm`,c:`dimmed`,children:`MuJoco Simulation on Web Assembly with Neural netwroks`}),(0,G.jsx)(hp,{w:`100%`}),(0,G.jsxs)(q,{children:[(0,G.jsx)(ed,{href:`https://github.com/ttktjmt/mjswan`,target:`_blank`,style:{fontWeight:`600`},children:`GitHub`}),`\xA0\xA0•\xA0\xA0`,(0,G.jsx)(ed,{href:`https://mjswan.readthedocs.io`,target:`_blank`,style:{fontWeight:`600`},children:`Documentation`})]}),(0,G.jsx)(hp,{w:`100%`}),(0,G.jsxs)(q,{style:{textAlign:`left`,maxHeight:`120px`,overflowY:`auto`,lineHeight:`1`,fontSize:`0.8rem`,opacity:`0.75`},px:`md`,children:[`Thanks to our contributors! `,(0,G.jsx)(`br`,{}),Eg.map((e,t)=>(0,G.jsxs)(`span`,{children:[(0,G.jsx)(ed,{href:e.html_url,target:`_blank`,style:{textDecoration:`none`,fontSize:`0.75rem`},children:e.login}),t<Eg.length-1&&`, `]},e.login))]})]})}),(0,G.jsxs)(Mg,{width:`20em`,visible:t,onVisibleChange:n,hiddenButtonTooltip:`Show controls (C)`,children:[(0,G.jsxs)(Mg.Handle,{children:[(0,G.jsx)(Gh,{label:`mjswan ${Tg}`,children:(0,G.jsx)(q,{component:`a`,onClick:e=>{e.stopPropagation(),M()},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{position:`absolute`,cursor:`pointer`,display:`flex`,top:`0.8em`,left:`0.9em`},children:(0,G.jsx)(vp,{src:`/logo.svg`,style:{width:`1.2em`,height:`auto`}})})}),(0,G.jsx)(`div`,{style:{width:`1.1em`}}),(0,G.jsx)(Mg.HideWhenCollapsed,{children:(0,G.jsxs)(q,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`,display:`flex`,alignItems:`center`,gap:`0.5em`},pt:`0.1em`,children:[(0,G.jsx)(`span`,{style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:a}),r.length>1&&(0,G.jsxs)(om,{position:`bottom-start`,offset:5,children:[(0,G.jsx)(om.Target,{children:(0,G.jsx)(q,{onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{cursor:`pointer`,display:`flex`,alignItems:`center`,flexShrink:0},children:(0,G.jsx)(bg,{size:16})})}),(0,G.jsx)(om.Dropdown,{onClick:e=>e.stopPropagation(),children:r.map(e=>(0,G.jsx)(om.Item,{onClick:t=>{t.stopPropagation(),o(e.value)},style:{fontWeight:e.value===i?600:400,backgroundColor:e.value===i?`rgba(34, 139, 230, 0.1)`:void 0},children:e.label},e.value))})]})]})}),(0,G.jsx)(Mg.HideWhenExpanded,{children:(0,G.jsx)(q,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`},pt:`0.1em`,children:a})}),(0,G.jsx)(Gh,{label:`Hide controls (C)`,children:(0,G.jsx)(ql,{variant:`subtle`,color:`gray`,size:`sm`,"aria-label":`Hide controls`,onClick:e=>{e.stopPropagation(),n(!1)},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),children:(0,G.jsx)(Cg,{size:14})})})]}),(0,G.jsx)(Mg.Contents,{children:(0,G.jsxs)(q,{pt:`0.375em`,children:[s.length>0&&(0,G.jsx)(Ng,{id:`scene-select`,label:`Scene`,children:(0,G.jsx)(qh,{id:`scene-select`,placeholder:`Select scene`,data:s,value:c,onChange:l,size:`xs`,radius:`xs`,searchable:!0,clearable:!1,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(u.length>0||d)&&(0,G.jsx)(Ng,{id:`splat-select`,label:`Splat`,children:(0,G.jsx)(Gh,{label:I??``,color:`red`,position:`bottom`,opened:I!==null,withArrow:!0,children:(0,G.jsx)(qh,{id:`splat-select`,placeholder:g===void 0?`Select splat`:`Select splat or paste .spz URL`,data:u,value:f,onChange:e=>{p(e),L(null),z(!1)},searchable:g!==void 0,searchValue:P,onSearchChange:e=>{F(e),e&&L(null)},onKeyDown:B,size:`xs`,radius:`xs`,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})})}),(m?.control&&f!==null||R)&&h&&(0,G.jsx)(Bg,{scale:m?.scale??1,xOffset:m?.xOffset??0,yOffset:m?.yOffset??0,zOffset:m?.zOffset??0,roll:m?.roll??0,pitch:m?.pitch??0,yaw:m?.yaw??0,onCalibrate:h}),_.length>0&&(0,G.jsx)(Ng,{id:`policy-select`,label:`Policy`,children:(0,G.jsx)(qh,{id:`policy-select`,placeholder:`Select policy`,data:_,value:v,onChange:y,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),x.length>0&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Ng,{id:`motion-select`,label:`Motion`,children:(0,G.jsx)(qh,{id:`motion-select`,placeholder:`Select motion`,data:x,value:S,onChange:C,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(0,G.jsx)(q,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(af,{label:`Show reference`,checked:w,onChange:e=>T(e.currentTarget.checked),size:`xs`})})]}),V.length>0&&D.some(e=>e.type===`slider`||e.type===`checkbox`)&&(0,G.jsx)(G.Fragment,{children:V.map(e=>{let t=te(e);return t.length===0?null:(0,G.jsx)(Pg,{label:Hg(e),expandByDefault:!0,children:t.map(e=>e.type===`checkbox`?(0,G.jsx)(Wg,{command:e,value:O[e.id]??0,onChange:k,disabled:!E},e.id):e.type===`slider`?(0,G.jsx)(Ug,{command:e,value:O[e.id]??0,onChange:k,disabled:!E,enabledWhenValue:e.enabledWhen?O[`${e.group}:${e.enabledWhen}`]:void 0},e.id):null)},e)})}),(0,G.jsx)(hp,{mb:`xs`,mx:`xs`}),(0,G.jsx)(q,{px:`xs`,pb:`xs`,children:(0,G.jsx)(xf,{variant:`light`,color:`red`,size:`xs`,fullWidth:!0,leftSection:(0,G.jsx)(Sg,{size:14}),onClick:ee,children:`Reset`})})]})})]})]})}function Kg(e,t,n){return Object.keys(e[t]).reduce((e,t)=>(e[t]=`var(--mantine-${n}-${t})`,e),{})}function qg(e,t){return e in t.breakpoints?t.breakpoints[e]:Be(e)}function Jg(e){let t=Wn(Ln,e),n=Kg(t,`fontSizes`,`font-size`),r=Kg(t,`lineHeights`,`line-height`),i=Kg(t,`shadows`,`shadow`),a=Kg(t,`radius`,`radius`),o=Kg(t,`spacing`,`spacing`),s=Object.keys(t.headings.sizes).reduce((e,t)=>(e[t]={fontSize:`var(--mantine-${t}-font-size)`,lineHeight:`var(--mantine-${t}-line-height)`,fontWeight:`var(--mantine-${t}-font-weight)`},e),{}),c=Object.keys(t.colors).reduce((e,t)=>(e[t]={0:`var(--mantine-color-${t}-0)`,1:`var(--mantine-color-${t}-1)`,2:`var(--mantine-color-${t}-2)`,3:`var(--mantine-color-${t}-3)`,4:`var(--mantine-color-${t}-4)`,5:`var(--mantine-color-${t}-5)`,6:`var(--mantine-color-${t}-6)`,7:`var(--mantine-color-${t}-7)`,8:`var(--mantine-color-${t}-8)`,9:`var(--mantine-color-${t}-9)`,filled:`var(--mantine-color-${t}-filled)`,filledHover:`var(--mantine-color-${t}-filled-hover)`,light:`var(--mantine-color-${t}-light)`,lightHover:`var(--mantine-color-${t}-light-hover)`,lightColor:`var(--mantine-color-${t}-light-color)`,outline:`var(--mantine-color-${t}-outline)`,outlineHover:`var(--mantine-color-${t}-outline-hover)`},e),{primary:`var(--mantine-primary-color-filled)`,primaryColors:{0:`var(--mantine-primary-color-0)`,1:`var(--mantine-primary-color-1)`,2:`var(--mantine-primary-color-2)`,3:`var(--mantine-primary-color-3)`,4:`var(--mantine-primary-color-4)`,5:`var(--mantine-primary-color-5)`,6:`var(--mantine-primary-color-6)`,7:`var(--mantine-primary-color-7)`,8:`var(--mantine-primary-color-8)`,9:`var(--mantine-primary-color-9)`,filled:`var(--mantine-primary-color-filled)`,filledHover:`var(--mantine-primary-color-filled-hover)`,light:`var(--mantine-primary-color-light)`,lightHover:`var(--mantine-primary-color-light-hover)`,lightColor:`var(--mantine-primary-color-light-color)`,outline:`var(--mantine-primary-color-outline)`,outlineHover:`var(--mantine-primary-color-outline-hover)`},white:`var(--mantine-color-white)`,black:`var(--mantine-color-black)`,text:`var(--mantine-color-text)`,body:`var(--mantine-color-body)`,error:`var(--mantine-color-error)`,placeholder:`var(--mantine-color-placeholder)`,anchor:`var(--mantine-color-anchor)`,default:`var(--mantine-color-default)`,defaultHover:`var(--mantine-color-default-hover)`,defaultColor:`var(--mantine-color-default-color)`,defaultBorder:`var(--mantine-color-default-border)`,dimmed:`var(--mantine-color-dimmed)`,disabledBody:`var(--mantine-color-disabled)`,disabledText:`var(--mantine-color-disabled-color)`,disabledBorder:`var(--mantine-color-disabled-border)`});return{scale:`var(--mantine-scale)`,cursorType:`var(--mantine-cursor-type)`,webkitFontSmoothing:`var(--mantine-webkit-font-smoothing)`,mozFontSmoothing:`var(--mantine-moz-font-smoothing)`,lineHeight:`var(--mantine-line-height)`,fontFamily:`var(--mantine-font-family)`,fontFamilyMonospace:`var(--mantine-font-family-monospace)`,fontFamilyHeadings:`var(--mantine-font-family-headings)`,headingFontWeight:`var(--mantine-heading-font-weight)`,radiusDefault:`var(--mantine-radius-default)`,breakpoints:t.breakpoints,fontSizes:n,lineHeights:r,shadows:i,radius:a,headings:s,spacing:o,colors:c,rtlSelector:`[dir="rtl"] &`,darkSelector:`[data-mantine-color-scheme="dark"] &`,lightSelector:`[data-mantine-color-scheme="light"] &`,smallerThan:e=>`(max-width: ${qg(e,t)})`,largerThan:e=>`(min-width: ${qg(e,t)})`}}var Yg=Nr({fontFamily:`Inter`,autoContrast:!0,components:{Checkbox:af.extend({defaultProps:{radius:`xs`}}),ColorInput:dp.extend({defaultProps:{radius:`xs`}}),Select:qh.extend({defaultProps:{radius:`sm`}}),Textarea:Hp.extend({defaultProps:{radius:`xs`}}),TextInput:_g.extend({defaultProps:{radius:`xs`}}),NumberInput:Dh.extend({defaultProps:{radius:`xs`}}),Paper:Xc.extend({defaultProps:{radius:`xs`,shadow:`0`}}),ActionIcon:ql.extend({defaultProps:{variant:`subtle`,color:`gray`,radius:`xs`}}),Button:xf.extend({defaultProps:{radius:`xs`,styles:{label:{fontWeight:450}}}})}});Jg(Yg);var Xg=(0,b.createContext)(void 0),Zg=()=>{let e=(0,b.useContext)(Xg);if(!e)throw Error(`useLoading must be used within a LoadingProvider`);return e},Qg=({children:e})=>{let[t,n]=(0,b.useState)(!1),[r,i]=(0,b.useState)(null),a=(0,b.useCallback)(e=>{e!==void 0&&i(e),n(!0)},[]),o=(0,b.useCallback)(e=>{i(e)},[]),s=(0,b.useCallback)(()=>{n(!1),i(null)},[]);return(0,G.jsx)(Xg.Provider,{value:{isLoading:t,loadingMessage:r,showLoading:a,setLoadingMessage:o,hideLoading:s},children:e})},$g=()=>{let{isLoading:e,loadingMessage:t}=Zg();return e?(0,G.jsx)(`div`,{className:`loader-overlay`,children:(0,G.jsxs)(`div`,{className:`loader-content`,children:[(0,G.jsx)(zl,{size:64,type:`bars`}),t&&(0,G.jsx)(`p`,{className:`loader-message`,children:t})]})}):null},e_=!1;function t_(){typeof window>`u`||(window.__mjswanReady=!0,e_||(e_=!0,window.dispatchEvent(new CustomEvent(`mjswan:ready`))))}function n_(){typeof window>`u`||(window.__mjswanError=!0)}var r_={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},i_={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},a_=`attached`,o_=`detached`,s_=1e3,c_=1001,l_=1002,u_=1003,d_=1004,f_=1004,p_=1005,m_=1005,h_=1006,g_=1007,__=1007,v_=1008,y_=1008,b_=1009,x_=1010,S_=1011,C_=1012,w_=1013,T_=1014,E_=1015,D_=1016,O_=1017,k_=1018,A_=1020,j_=35902,M_=35899,N_=1021,P_=1022,F_=1023,I_=1026,L_=1027,R_=1028,z_=1029,B_=1030,V_=1031,H_=1032,U_=1033,W_=33776,G_=33777,K_=33778,q_=33779,J_=35840,Y_=35841,X_=35842,Z_=35843,Q_=36196,$_=37492,ev=37496,tv=37808,nv=37809,rv=37810,iv=37811,av=37812,ov=37813,sv=37814,cv=37815,lv=37816,uv=37817,dv=37818,fv=37819,pv=37820,mv=37821,hv=36492,gv=36494,_v=36495,vv=36283,yv=36284,bv=36285,xv=36286,Sv=2200,Cv=2201,wv=2202,Tv=2300,Ev=2301,Dv=2302,Ov=2400,kv=2401,Av=2402,jv=2500,Mv=2501,Nv=3200,Pv=3201,Fv=3202,Iv=3203,Lv=`srgb`,Rv=`srgb-linear`,zv=`linear`,Bv=`srgb`,Vv=7680,Hv=7681,Uv=7682,Wv=7683,Gv=34055,Kv=34056,qv=5386,Jv=35044,Yv=35048,Xv=35040,Zv=35045,Qv=35049,$v=35041,ey=35046,ty=35050,ny=35042,ry=`300 es`,iy=2e3,ay=2001,oy={COMPUTE:`compute`,RENDER:`render`},sy={PERSPECTIVE:`perspective`,LINEAR:`linear`,FLAT:`flat`},cy={NORMAL:`normal`,CENTROID:`centroid`,SAMPLE:`sample`,FIRST:`first`,EITHER:`either`};function ly(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}var uy={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function dy(e,t){return new uy[e](t)}function fy(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function py(){let e=fy(`canvas`);return e.style.display=`block`,e}var my={},hy=null;function gy(e){hy=e}function _y(){return hy}function vy(...e){let t=`THREE.`+e.shift();hy?hy(`log`,t,...e):console.log(t,...e)}function yy(...e){let t=`THREE.`+e.shift();hy?hy(`warn`,t,...e):console.warn(t,...e)}function by(...e){let t=`THREE.`+e.shift();hy?hy(`error`,t,...e):console.error(t,...e)}function xy(...e){let t=e.join(` `);t in my||(my[t]=!0,yy(...e))}function Sy(e,t,n){return new Promise(function(r,i){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()}}setTimeout(a,n)})}var Cy=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?!1: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<r;n++)t[n].call(this,e);e.target=null}}},wy=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),Ty=1234567,Ey=Math.PI/180,Dy=180/Math.PI;function Oy(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(wy[e&255]+wy[e>>8&255]+wy[e>>16&255]+wy[e>>24&255]+`-`+wy[t&255]+wy[t>>8&255]+`-`+wy[t>>16&15|64]+wy[t>>24&255]+`-`+wy[n&63|128]+wy[n>>8&255]+`-`+wy[n>>16&255]+wy[n>>24&255]+wy[r&255]+wy[r>>8&255]+wy[r>>16&255]+wy[r>>24&255]).toLowerCase()}function ky(e,t,n){return Math.max(t,Math.min(n,e))}function Ay(e,t){return(e%t+t)%t}function jy(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function My(e,t,n){return e===t?0:(n-e)/(t-e)}function Ny(e,t,n){return(1-n)*e+n*t}function Py(e,t,n,r){return Ny(e,t,1-Math.exp(-n*r))}function Fy(e,t=1){return t-Math.abs(Ay(e,t*2)-t)}function Iy(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function Ly(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function Ry(e,t){return e+Math.floor(Math.random()*(t-e+1))}function zy(e,t){return e+Math.random()*(t-e)}function By(e){return e*(.5-Math.random())}function Vy(e){e!==void 0&&(Ty=e);let t=Ty+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Hy(e){return e*Ey}function Uy(e){return e*Dy}function Wy(e){return(e&e-1)==0&&e!==0}function Gy(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function Ky(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function qy(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:yy(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function Jy(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 Yy(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var Xy={DEG2RAD:Ey,RAD2DEG:Dy,generateUUID:Oy,clamp:ky,euclideanModulo:Ay,mapLinear:jy,inverseLerp:My,lerp:Ny,damp:Py,pingpong:Fy,smoothstep:Iy,smootherstep:Ly,randInt:Ry,randFloat:zy,randFloatSpread:By,seededRandom:Vy,degToRad:Hy,radToDeg:Uy,isPowerOfTwo:Wy,ceilPowerOfTwo:Gy,floorPowerOfTwo:Ky,setQuaternionFromProperEuler:qy,normalize:Yy,denormalize:Jy},J=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=ky(this.x,e.x,t.x),this.y=ky(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ky(this.x,e,t),this.y=ky(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ky(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(ky(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}},Zy=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){e[t+0]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u;return}if(o>=1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;return}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,o=Math.sin(o*n)/r,s=s*t+d*o,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:yy(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&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(ky(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}},Y=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($y.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion($y.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=ky(this.x,e.x,t.x),this.y=ky(this.y,e.y,t.y),this.z=ky(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ky(this.x,e,t),this.y=ky(this.y,e,t),this.z=ky(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ky(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 Qy.copy(this).projectOnVector(e),this.sub(Qy)}reflect(e){return this.sub(Qy.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(ky(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,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-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}},Qy=new Y,$y=new Zy,eb=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(tb.makeScale(e,t)),this}rotate(e){return this.premultiply(tb.makeRotation(-e)),this}translate(e,t){return this.premultiply(tb.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)}},tb=new eb,nb=new eb().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),rb=new eb().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ib(){let e={enabled:!0,workingColorSpace:Rv,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=ob(e.r),e.g=ob(e.g),e.b=ob(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===`srgb`&&(e.r=sb(e.r),e.g=sb(e.g),e.b=sb(e.b)),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===``?zv: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 xy(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return xy(`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({[Rv]:{primaries:t,whitePoint:r,transfer:zv,toXYZ:nb,fromXYZ:rb,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Lv},outputColorSpaceConfig:{drawingBufferColorSpace:Lv}},[Lv]:{primaries:t,whitePoint:r,transfer:Bv,toXYZ:nb,fromXYZ:rb,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Lv}}}),e}var ab=ib();function ob(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function sb(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var cb,lb=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{cb===void 0&&(cb=fy(`canvas`)),cb.width=e.width,cb.height=e.height;let t=cb.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=cb}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=fy(`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;e<i.length;e++)i[e]=ob(i[e]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(ob(t[e]/255)*255):t[e]=ob(t[e]);return{data:t,width:e.width,height:e.height}}else return yy(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},ub=0,db=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ub++}),this.uuid=Oy(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(fb(r[t].image)):e.push(fb(r[t]))}else e=fb(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function fb(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?lb.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(yy(`Texture: Unable to serialize Texture.`),{})}var pb=0,mb=new Y,hb=class e extends Cy{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=c_,i=c_,a=h_,o=v_,s=F_,c=b_,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:pb++}),this.uuid=Oy(),this.name=``,this.source=new db(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new J(0,0),this.repeat=new J(1,1),this.center=new J(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new eb,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(mb).x}get height(){return this.source.getSize(mb).y}get depth(){return this.source.getSize(mb).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){yy(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){yy(`Texture.setValues(): property '${t}' does not exist.`);continue}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 s_:e.x-=Math.floor(e.x);break;case c_:e.x=e.x<0?0:1;break;case l_:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case s_:e.y-=Math.floor(e.y);break;case c_:e.y=e.y<0?0:1;break;case l_:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};hb.DEFAULT_IMAGE=null,hb.DEFAULT_MAPPING=300,hb.DEFAULT_ANISOTROPY=1;var gb=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)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ky(this.x,e.x,t.x),this.y=ky(this.y,e.y,t.y),this.z=ky(this.z,e.z,t.z),this.w=ky(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ky(this.x,e,t),this.y=ky(this.y,e,t),this.z=ky(this.z,e,t),this.w=ky(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ky(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,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.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},_b=class extends Cy{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:h_,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new gb(0,0,e,t),this.scissorTest=!1,this.viewport=new gb(0,0,e,t);let r=new hb({width:e,height:t,depth:n.depth});this.textures=[];let i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:h_,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);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<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new db(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:`dispose`})}},vb=class extends _b{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},yb=class extends hb{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=u_,this.minFilter=u_,this.wrapR=c_,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},bb=class extends vb{constructor(e=1,t=1,n=1,r={}){super(e,t,r),this.isWebGLArrayRenderTarget=!0,this.depth=n,this.texture=new yb(null,e,t,n),this._setTextureOptions(r),this.texture.isRenderTargetTexture=!0}},xb=class extends hb{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=u_,this.minFilter=u_,this.wrapR=c_,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Sb=class extends vb{constructor(e=1,t=1,n=1,r={}){super(e,t,r),this.isWebGL3DRenderTarget=!0,this.depth=n,this.texture=new xb(null,e,t,n),this._setTextureOptions(r),this.texture.isRenderTargetTexture=!0}},Cb=class{constructor(e=new Y(1/0,1/0,1/0),t=new Y(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Tb.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Tb.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Tb.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,Tb):Tb.fromBufferAttribute(r,t),Tb.applyMatrix4(e.matrixWorld),this.expandByPoint(Tb);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Eb.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Eb.copy(e.boundingBox)),Eb.applyMatrix4(e.matrixWorld),this.union(Eb)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=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,Tb),Tb.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(Nb),Pb.subVectors(this.max,Nb),Db.subVectors(e.a,Nb),Ob.subVectors(e.b,Nb),kb.subVectors(e.c,Nb),Ab.subVectors(Ob,Db),jb.subVectors(kb,Ob),Mb.subVectors(Db,kb);let t=[0,-Ab.z,Ab.y,0,-jb.z,jb.y,0,-Mb.z,Mb.y,Ab.z,0,-Ab.x,jb.z,0,-jb.x,Mb.z,0,-Mb.x,-Ab.y,Ab.x,0,-jb.y,jb.x,0,-Mb.y,Mb.x,0];return!Lb(t,Db,Ob,kb,Pb)||(t=[1,0,0,0,1,0,0,0,1],!Lb(t,Db,Ob,kb,Pb))?!1:(Fb.crossVectors(Ab,jb),t=[Fb.x,Fb.y,Fb.z],Lb(t,Db,Ob,kb,Pb))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Tb).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Tb).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(wb[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wb[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wb[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wb[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wb[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wb[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wb[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wb[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wb),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}},wb=[new Y,new Y,new Y,new Y,new Y,new Y,new Y,new Y],Tb=new Y,Eb=new Cb,Db=new Y,Ob=new Y,kb=new Y,Ab=new Y,jb=new Y,Mb=new Y,Nb=new Y,Pb=new Y,Fb=new Y,Ib=new Y;function Lb(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Ib.fromArray(e,a);let o=i.x*Math.abs(Ib.x)+i.y*Math.abs(Ib.y)+i.z*Math.abs(Ib.z),s=t.dot(Ib),c=n.dot(Ib),l=r.dot(Ib);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var Rb=new Cb,zb=new Y,Bb=new Y,Vb=class{constructor(e=new Y,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?Rb.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.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;zb.subVectors(e,this.center);let t=zb.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(zb,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Bb.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(zb.copy(e.center).add(Bb)),this.expandByPoint(zb.copy(e.center).sub(Bb))),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}},Hb=new Y,Ub=new Y,Wb=new Y,Gb=new Y,Kb=new Y,qb=new Y,Jb=new Y,Yb=class{constructor(e=new Y,t=new Y(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,Hb)),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=Hb.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Hb.copy(this.origin).addScaledVector(this.direction,t),Hb.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){Ub.copy(e).add(t).multiplyScalar(.5),Wb.copy(t).sub(e).normalize(),Gb.copy(this.origin).sub(Ub);let i=e.distanceTo(t)*.5,a=-this.direction.dot(Wb),o=Gb.dot(this.direction),s=-Gb.dot(Wb),c=Gb.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(Ub).addScaledVector(Wb,d),f}intersectSphere(e,t){Hb.subVectors(e.center,this.origin);let n=Hb.dot(this.direction),r=Hb.dot(Hb)-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?!1: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||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||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=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)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Hb)!==null}intersectTriangle(e,t,n,r,i){Kb.subVectors(t,e),qb.subVectors(n,e),Jb.crossVectors(Kb,qb);let a=this.direction.dot(Jb),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Gb.subVectors(this.origin,e);let s=o*this.direction.dot(qb.crossVectors(Gb,qb));if(s<0)return null;let c=o*this.direction.dot(Kb.cross(Gb));if(c<0||s+c>a)return null;let l=-o*Gb.dot(Jb);return l<0?null:this.at(l/a,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)}},Xb=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/Zb.setFromMatrixColumn(e,0).length(),i=1/Zb.setFromMatrixColumn(e,1).length(),a=1/Zb.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($b,e,ex)}lookAt(e,t,n){let r=this.elements;return rx.subVectors(e,t),rx.lengthSq()===0&&(rx.z=1),rx.normalize(),tx.crossVectors(n,rx),tx.lengthSq()===0&&(Math.abs(n.z)===1?rx.x+=1e-4:rx.z+=1e-4,rx.normalize(),tx.crossVectors(n,rx)),tx.normalize(),nx.crossVectors(rx,tx),r[0]=tx.x,r[4]=nx.x,r[8]=rx.x,r[1]=tx.y,r[5]=nx.y,r[9]=rx.y,r[2]=tx.z,r[6]=nx.z,r[10]=rx.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],P=r[7],F=r[11],I=r[15];return i[0]=a*x+o*T+s*k+c*N,i[4]=a*S+o*E+s*A+c*P,i[8]=a*C+o*D+s*j+c*F,i[12]=a*w+o*O+s*M+c*I,i[1]=l*x+u*T+d*k+f*N,i[5]=l*S+u*E+d*A+f*P,i[9]=l*C+u*D+d*j+f*F,i[13]=l*w+u*O+d*M+f*I,i[2]=p*x+m*T+h*k+g*N,i[6]=p*S+m*E+h*A+g*P,i[10]=p*C+m*D+h*j+g*F,i[14]=p*w+m*O+h*M+g*I,i[3]=_*x+v*T+y*k+b*N,i[7]=_*S+v*E+y*A+b*P,i[11]=_*C+v*D+y*j+b*F,i[15]=_*w+v*O+y*M+b*I,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],p=e[3],m=e[7],h=e[11],g=e[15];return p*(+i*s*u-r*c*u-i*o*d+n*c*d+r*o*f-n*s*f)+m*(+t*s*f-t*c*d+i*a*d-r*a*f+r*c*l-i*s*l)+h*(+t*c*u-t*o*f-i*a*u+n*a*f+i*o*l-n*c*l)+g*(-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=Zb.set(r[0],r[1],r[2]).length(),a=Zb.set(r[4],r[5],r[6]).length(),o=Zb.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],Qb.copy(this);let s=1/i,c=1/a,l=1/o;return Qb.elements[0]*=s,Qb.elements[1]*=s,Qb.elements[2]*=s,Qb.elements[4]*=c,Qb.elements[5]*=c,Qb.elements[6]*=c,Qb.elements[8]*=l,Qb.elements[9]*=l,Qb.elements[10]*=l,t.setFromRotationMatrix(Qb),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a,o=iy,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===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);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=iy,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===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);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}},Zb=new Y,Qb=new Xb,$b=new Y(0,0,0),ex=new Y(1,1,1),tx=new Y,nx=new Y,rx=new Y,ix=new Xb,ax=new Zy,ox=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(ky(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(-ky(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(ky(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(-ky(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(ky(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(-ky(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:yy(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return ix.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ix,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ax.setFromEuler(this),this.setFromQuaternion(ax,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}};ox.DEFAULT_ORDER=`XYZ`;var sx=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!=0}},cx=0,lx=new Y,ux=new Zy,dx=new Xb,fx=new Y,px=new Y,mx=new Y,hx=new Zy,gx=new Y(1,0,0),_x=new Y(0,1,0),vx=new Y(0,0,1),yx={type:`added`},bx={type:`removed`},xx={type:`childadded`,child:null},Sx={type:`childremoved`,child:null},Cx=class e extends Cy{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:cx++}),this.uuid=Oy(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new Y,n=new ox,r=new Zy,i=new Y(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Xb},normalMatrix:{value:new eb}}),this.matrix=new Xb,this.matrixWorld=new Xb,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new sx,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return ux.setFromAxisAngle(e,t),this.quaternion.multiply(ux),this}rotateOnWorldAxis(e,t){return ux.setFromAxisAngle(e,t),this.quaternion.premultiply(ux),this}rotateX(e){return this.rotateOnAxis(gx,e)}rotateY(e){return this.rotateOnAxis(_x,e)}rotateZ(e){return this.rotateOnAxis(vx,e)}translateOnAxis(e,t){return lx.copy(e).applyQuaternion(this.quaternion),this.position.add(lx.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(gx,e)}translateY(e){return this.translateOnAxis(_x,e)}translateZ(e){return this.translateOnAxis(vx,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(dx.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?fx.copy(e):fx.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),px.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?dx.lookAt(px,fx,this.up):dx.lookAt(fx,px,this.up),this.quaternion.setFromRotationMatrix(dx),r&&(dx.extractRotation(r.matrixWorld),ux.setFromRotationMatrix(dx),this.quaternion.premultiply(ux.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(by(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(yx),xx.child=e,this.dispatchEvent(xx),xx.child=null):by(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(bx),Sx.child=e,this.dispatchEvent(Sx),Sx.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),dx.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),dx.multiply(e.parent.matrixWorld)),e.applyMatrix4(dx),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(yx),xx.child=e,this.dispatchEvent(xx),xx.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(px,e,mx),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(px,hx,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let e=this.children;for(let t=0,n=e.length;t<n;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==``&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(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()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(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&&this.environment.isRenderTargetTexture!==!0&&(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;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(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)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}};Cx.DEFAULT_UP=new Y(0,1,0),Cx.DEFAULT_MATRIX_AUTO_UPDATE=!0,Cx.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var wx=new Y,Tx=new Y,Ex=new Y,Dx=new Y,Ox=new Y,kx=new Y,Ax=new Y,jx=new Y,Mx=new Y,Nx=new Y,Px=new gb,Fx=new gb,Ix=new gb,Lx=class e{constructor(e=new Y,t=new Y,n=new Y){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),wx.subVectors(e,t),r.cross(wx);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){wx.subVectors(r,t),Tx.subVectors(n,t),Ex.subVectors(e,t);let a=wx.dot(wx),o=wx.dot(Tx),s=wx.dot(Ex),c=Tx.dot(Tx),l=Tx.dot(Ex),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,Dx)===null?!1:Dx.x>=0&&Dx.y>=0&&Dx.x+Dx.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Dx)===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,Dx.x),s.addScaledVector(a,Dx.y),s.addScaledVector(o,Dx.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Px.setScalar(0),Fx.setScalar(0),Ix.setScalar(0),Px.fromBufferAttribute(e,t),Fx.fromBufferAttribute(e,n),Ix.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Px,i.x),a.addScaledVector(Fx,i.y),a.addScaledVector(Ix,i.z),a}static isFrontFacing(e,t,n,r){return wx.subVectors(n,t),Tx.subVectors(e,t),wx.cross(Tx).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 wx.subVectors(this.c,this.b),Tx.subVectors(this.a,this.b),wx.cross(Tx).length()*.5}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;Ox.subVectors(r,n),kx.subVectors(i,n),jx.subVectors(e,n);let s=Ox.dot(jx),c=kx.dot(jx);if(s<=0&&c<=0)return t.copy(n);Mx.subVectors(e,r);let l=Ox.dot(Mx),u=kx.dot(Mx);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(Ox,a);Nx.subVectors(e,i);let f=Ox.dot(Nx),p=kx.dot(Nx);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(kx,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Ax.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Ax,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Ox,a).addScaledVector(kx,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Rx={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},zx={h:0,s:0,l:0},Bx={h:0,s:0,l:0};function Vx(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var X=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=Lv){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,ab.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=ab.workingColorSpace){return this.r=e,this.g=t,this.b=n,ab.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=ab.workingColorSpace){if(e=Ay(e,1),t=ky(t,0,1),n=ky(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=Vx(i,r,e+1/3),this.g=Vx(i,r,e),this.b=Vx(i,r,e-1/3)}return ab.colorSpaceToWorking(this,r),this}setStyle(e,t=Lv){function n(t){t!==void 0&&parseFloat(t)<1&&yy(`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:yy(`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);yy(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Lv){let n=Rx[e.toLowerCase()];return n===void 0?yy(`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=ob(e.r),this.g=ob(e.g),this.b=ob(e.b),this}copyLinearToSRGB(e){return this.r=sb(e.r),this.g=sb(e.g),this.b=sb(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Lv){return ab.workingToColorSpace(Hx.copy(this),e),Math.round(ky(Hx.r*255,0,255))*65536+Math.round(ky(Hx.g*255,0,255))*256+Math.round(ky(Hx.b*255,0,255))}getHexString(e=Lv){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ab.workingColorSpace){ab.workingToColorSpace(Hx.copy(this),t);let n=Hx.r,r=Hx.g,i=Hx.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+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4;break}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=ab.workingColorSpace){return ab.workingToColorSpace(Hx.copy(this),t),e.r=Hx.r,e.g=Hx.g,e.b=Hx.b,e}getStyle(e=Lv){ab.workingToColorSpace(Hx.copy(this),e);let t=Hx.r,n=Hx.g,r=Hx.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(zx),this.setHSL(zx.h+e,zx.s+t,zx.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(zx),e.getHSL(Bx);let n=Ny(zx.h,Bx.h,t),r=Ny(zx.s,Bx.s,t),i=Ny(zx.l,Bx.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Hx=new X;X.NAMES=Rx;var Ux=0,Wx=class extends Cy{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Ux++}),this.uuid=Oy(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new X(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Vv,this.stencilZFail=Vv,this.stencilZPass=Vv,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=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){yy(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){yy(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}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`}};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),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(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),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(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!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(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),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(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){e===!0&&this.version++}},Gx=class extends Wx{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new X(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 ox,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}},Kx=qx();function qx(){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[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=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(;!(t&8388608);)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}}function Jx(e){Math.abs(e)>65504&&yy(`DataUtils.toHalfFloat(): Value out of range.`),e=ky(e,-65504,65504),Kx.floatView[0]=e;let t=Kx.uint32View[0],n=t>>23&511;return Kx.baseTable[n]+((t&8388607)>>Kx.shiftTable[n])}function Yx(e){let t=e>>10;return Kx.uint32View[0]=Kx.mantissaTable[Kx.offsetTable[t]+(e&1023)]+Kx.exponentTable[t],Kx.floatView[0]}var Xx=class{static toHalfFloat(e){return Jx(e)}static fromHalfFloat(e){return Yx(e)}},Zx=new Y,Qx=new J,$x=0,eS=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:$x++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Jv,this.updateRanges=[],this.gpuType=E_,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&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;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Qx.fromBufferAttribute(this,t),Qx.applyMatrix3(e),this.setXY(t,Qx.x,Qx.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.applyMatrix3(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.applyMatrix4(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.applyNormalMatrix(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.transformDirection(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Jy(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Yy(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Jy(t,this.array)),t}setX(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Jy(t,this.array)),t}setY(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Jy(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Jy(t,this.array)),t}setW(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array),i=Yy(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==``&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}},tS=class extends eS{constructor(e,t,n){super(new Int8Array(e),t,n)}},nS=class extends eS{constructor(e,t,n){super(new Uint8Array(e),t,n)}},rS=class extends eS{constructor(e,t,n){super(new Uint8ClampedArray(e),t,n)}},iS=class extends eS{constructor(e,t,n){super(new Int16Array(e),t,n)}},aS=class extends eS{constructor(e,t,n){super(new Uint16Array(e),t,n)}},oS=class extends eS{constructor(e,t,n){super(new Int32Array(e),t,n)}},sS=class extends eS{constructor(e,t,n){super(new Uint32Array(e),t,n)}},cS=class extends eS{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=Yx(this.array[e*this.itemSize]);return this.normalized&&(t=Jy(t,this.array)),t}setX(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize]=Jx(t),this}getY(e){let t=Yx(this.array[e*this.itemSize+1]);return this.normalized&&(t=Jy(t,this.array)),t}setY(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+1]=Jx(t),this}getZ(e){let t=Yx(this.array[e*this.itemSize+2]);return this.normalized&&(t=Jy(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+2]=Jx(t),this}getW(e){let t=Yx(this.array[e*this.itemSize+3]);return this.normalized&&(t=Jy(t,this.array)),t}setW(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+3]=Jx(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array)),this.array[e+0]=Jx(t),this.array[e+1]=Jx(n),this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array)),this.array[e+0]=Jx(t),this.array[e+1]=Jx(n),this.array[e+2]=Jx(r),this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array),i=Yy(i,this.array)),this.array[e+0]=Jx(t),this.array[e+1]=Jx(n),this.array[e+2]=Jx(r),this.array[e+3]=Jx(i),this}},lS=class extends eS{constructor(e,t,n){super(new Float32Array(e),t,n)}},uS=0,dS=new Xb,fS=new Cx,pS=new Y,mS=new Cb,hS=new Cb,gS=new Y,_S=class e extends Cy{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:uS++}),this.uuid=Oy(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(ly(e)?sS:aS)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new eb().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return dS.makeRotationFromQuaternion(e),this.applyMatrix4(dS),this}rotateX(e){return dS.makeRotationX(e),this.applyMatrix4(dS),this}rotateY(e){return dS.makeRotationY(e),this.applyMatrix4(dS),this}rotateZ(e){return dS.makeRotationZ(e),this.applyMatrix4(dS),this}translate(e,t,n){return dS.makeTranslation(e,t,n),this.applyMatrix4(dS),this}scale(e,t,n){return dS.makeScale(e,t,n),this.applyMatrix4(dS),this}lookAt(e){return fS.lookAt(e),fS.updateMatrix(),this.applyMatrix4(fS.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(pS).negate(),this.translate(pS.x,pS.y,pS.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new lS(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&yy(`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 Cb);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){by(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new Y(-1/0,-1/0,-1/0),new Y(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];mS.setFromBufferAttribute(n),this.morphTargetsRelative?(gS.addVectors(this.boundingBox.min,mS.min),this.boundingBox.expandByPoint(gS),gS.addVectors(this.boundingBox.max,mS.max),this.boundingBox.expandByPoint(gS)):(this.boundingBox.expandByPoint(mS.min),this.boundingBox.expandByPoint(mS.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&by(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Vb);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){by(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new Y,1/0);return}if(e){let n=this.boundingSphere.center;if(mS.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];hS.setFromBufferAttribute(n),this.morphTargetsRelative?(gS.addVectors(mS.min,hS.min),mS.expandByPoint(gS),gS.addVectors(mS.max,hS.max),mS.expandByPoint(gS)):(mS.expandByPoint(hS.min),mS.expandByPoint(hS.max))}mS.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)gS.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(gS));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)gS.fromBufferAttribute(a,t),o&&(pS.fromBufferAttribute(e,t),gS.add(pS)),r=Math.max(r,n.distanceToSquared(gS))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&by(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){by(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv;this.hasAttribute(`tangent`)===!1&&this.setAttribute(`tangent`,new eS(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new Y,s[e]=new Y;let c=new Y,l=new Y,u=new Y,d=new J,f=new J,p=new J,m=new Y,h=new Y;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new Y,y=new Y,b=new Y,x=new Y;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0)n=new eS(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new Y,i=new Y,a=new Y,o=new Y,s=new Y,c=new Y,l=new Y,u=new Y;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)gS.fromBufferAttribute(e,t),gS.normalize(),e.setXYZ(t,gS.x,gS.y,gS.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new eS(a,r,i)}if(this.index===null)return yy(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.type,this.name!==``&&(e.name=this.name),Object.keys(this.userData).length>0&&(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;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(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;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:`dispose`})}},vS=new Xb,yS=new Yb,bS=new Vb,xS=new Y,SS=new Y,CS=new Y,wS=new Y,TS=new Y,ES=new Y,DS=new Y,OS=new Y,kS=class extends Cx{constructor(e=new _S,t=new Gx){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){ES.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(TS.fromBufferAttribute(s,e),a?ES.addScaledVector(TS,r):ES.addScaledVector(TS.sub(t),r))}t.add(ES)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),bS.copy(n.boundingSphere),bS.applyMatrix4(i),yS.copy(e.ray).recast(e.near),!(bS.containsPoint(yS.origin)===!1&&(yS.intersectSphere(bS,xS)===null||yS.origin.distanceToSquared(xS)>(e.far-e.near)**2))&&(vS.copy(i).invert(),yS.copy(e.ray).applyMatrix4(vS),!(n.boundingBox!==null&&yS.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,yS)))}_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;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=jS(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=jS(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(s!==void 0)if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=jS(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=jS(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function AS(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;OS.copy(s),OS.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(OS);return l<n.near||l>n.far?null:{distance:l,point:OS.clone(),object:e}}function jS(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,SS),e.getVertexPosition(c,CS),e.getVertexPosition(l,wS);let u=AS(e,t,n,r,SS,CS,wS,DS);if(u){let e=new Y;Lx.getBarycoord(DS,SS,CS,wS,e),i&&(u.uv=Lx.getInterpolatedAttribute(i,s,c,l,e,new J)),a&&(u.uv1=Lx.getInterpolatedAttribute(a,s,c,l,e,new J)),o&&(u.normal=Lx.getInterpolatedAttribute(o,s,c,l,e,new Y),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new Y,materialIndex:0};Lx.getNormal(SS,CS,wS,t.normal),u.face=t,u.barycoord=e}return u}var MS=class e extends _S{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;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new lS(c,3)),this.setAttribute(`normal`,new lS(l,3)),this.setAttribute(`uv`,new lS(u,2));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 Y;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?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;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};function NS(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(yy(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone():Array.isArray(i)?t[n][r]=i.slice():t[n][r]=i}}return t}function PS(e){let t={};for(let n=0;n<e.length;n++){let r=NS(e[n]);for(let e in r)t[e]=r[e]}return t}function FS(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function IS(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:ab.workingColorSpace}var LS={clone:NS,merge:PS},RS=`void main() {
61
+ `),a=!1),Object.assign(Object.assign({},e),{allowNegative:a})}function dh(e){e=uh(e),e.decimalSeparator,e.allowedDecimalSeparators,e.thousandsGroupStyle;var t=e.suffix,n=e.allowNegative,r=e.allowLeadingZeros,i=e.onKeyDown;i===void 0&&(i=Em);var a=e.onBlur;a===void 0&&(a=Em);var o=e.thousandSeparator,s=e.decimalScale,c=e.fixedDecimalScale,l=e.prefix;l===void 0&&(l=``);var u=e.defaultValue,d=e.value,f=e.valueIsNumericString,p=e.onValueChange,m=wm(e,[`decimalSeparator`,`allowedDecimalSeparators`,`thousandsGroupStyle`,`suffix`,`allowNegative`,`allowLeadingZeros`,`onKeyDown`,`onBlur`,`thousandSeparator`,`decimalScale`,`fixedDecimalScale`,`prefix`,`defaultValue`,`value`,`valueIsNumericString`,`onValueChange`]),h=ih(e),g=h.decimalSeparator,_=h.allowedDecimalSeparators,v=function(t){return rh(t,e)},y=function(t,n){return ch(t,n,e)},b=km(d)?u:d,x=f??sh(b,l,t);km(d)?km(u)||(x||=typeof u==`number`):x||=typeof d==`number`;var S=function(e){return jm(e)?e:(typeof e==`number`&&(e=Bm(e)),x&&typeof s==`number`?Vm(e,s,!!c):e)},C=$m(S(d),S(u),!!x,v,y,p),w=C[0],T=w.numAsString,E=w.formattedValue,D=C[1];return Object.assign(Object.assign({},m),{value:E,valueIsNumericString:!1,isValidInputCharacter:function(e){return e===g?!0:Om(e)},isCharacterSame:function(e){var t=e.currentValue,n=e.lastValue,r=e.formattedValue,i=e.currentValueIndex,a=e.formattedValueIndex,o=t[i],u=r[a],f=Um(n,t).to,p=function(e){return y(e).indexOf(`.`)+l.length};return d===0&&c&&s&&t[f.start]===g&&p(t)<i&&p(r)>a?!1:i>=f.start&&i<f.end&&_&&_.includes(o)&&u===g?!0:o===u},onValueChange:D,format:v,removeFormatting:y,getCaretBoundary:function(t){return lh(t,e)},onKeyDown:function(e){var t=e.target,r=e.key,a=t.selectionStart,u=t.selectionEnd,d=t.value;if(d===void 0&&(d=``),(r===`Backspace`||r===`Delete`)&&u<l.length&&d!==`-`){e.preventDefault();return}if(a!==u){i(e);return}r===`Backspace`&&d[0]===`-`&&a===l.length+1&&n&&Hm(t,1),s&&c&&(r===`Backspace`&&d[a-1]===g?(Hm(t,a-1),e.preventDefault()):r===`Delete`&&d[a]===g&&e.preventDefault()),_?.includes(r)&&d[a]===g&&Hm(t,a+1);var f=o===!0?`,`:o;r===`Backspace`&&d[a-1]===f&&Hm(t,a-1),r===`Delete`&&d[a]===f&&Hm(t,a+1),i(e)},onBlur:function(t){var n=T;n.match(/\d/g)||(n=``),r||(n=Lm(n)),c&&s&&(n=Vm(n,s,c)),n!==T&&D({formattedValue:rh(n,e),value:n,floatValue:parseFloat(n)},{event:t,source:Tm.event}),a(t)}})}function fh(e){var t=dh(e);return b.createElement(nh,Object.assign({},t))}var ph={root:`m_e2f5cd4e`,controls:`m_95e17d22`,control:`m_80b4b171`};function mh({direction:e,style:t,...n}){return(0,G.jsx)(`svg`,{style:{width:`var(--ni-chevron-size)`,height:`var(--ni-chevron-size)`,transform:e===`up`?`rotate(180deg)`:void 0,...t},viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...n,children:(0,G.jsx)(`path`,{d:`M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}var hh=/^(0\.0*|-0(\.0*)?)$/,gh=/^-?0\d+(\.\d+)?\.?$/,_h=/\.\d*0$/,vh=/^-?\d+\.$/;function yh(e){return typeof e==`string`&&e!==``&&!Number.isNaN(Number(e))}function bh(e){return typeof e==`number`?e<2**53-1:e===``||yh(e)&&Number(e)<2**53-1}function xh(e){return e.toString().replace(`.`,``).length}function Sh(e,t){return(typeof e==`number`?e<2**53-1:!Number.isNaN(Number(e)))&&!Number.isNaN(e)&&xh(t)<14&&t!==``}function Ch(e,t,n){return e===void 0?!0:(t===void 0||e>=t)&&(n===void 0||e<=n)}var wh={step:1,clampBehavior:`blur`,allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0,allowedDecimalSeparators:[`.`,`,`]},Th=en((e,{size:t})=>({controls:{"--ni-chevron-size":nt(t,`ni-chevron-size`)}}));function Eh(e,t,n){let r=e.toString(),i=vh.test(r),a=r.replace(/^0+(?=\d)/,``),o=parseFloat(a);if(Number.isNaN(o))return a;if(o>2**53-1)return t===void 0?a:t;let s=ut(o,n,t);return i?`${s.toString().replace(/^0+(?=\d)/,``)}.`:s}var Dh=_i((e,t)=>{let n=K(`NumberInput`,wh,e),{className:r,classNames:i,styles:a,unstyled:o,vars:s,onChange:c,onValueChange:l,value:u,defaultValue:d,max:f,min:p,step:m,hideControls:h,rightSection:g,isAllowed:_,clampBehavior:v,onBlur:y,allowDecimal:x,decimalScale:S,onKeyDown:C,onKeyDownCapture:w,handlersRef:T,startValue:E,disabled:D,rightSectionPointerEvents:O,allowNegative:k,readOnly:A,size:j,rightSectionWidth:M,stepHoldInterval:N,stepHoldDelay:P,allowLeadingZeros:F,withKeyboardEvents:I,trimLeadingZeroesOnBlur:L,allowedDecimalSeparators:R,attributes:z,...B}=n,V=jr({name:`NumberInput`,classes:ph,props:n,classNames:i,styles:a,unstyled:o,attributes:z,vars:s,varsResolver:Th}),{resolvedClassNames:ee,resolvedStyles:te}=mr({classNames:i,styles:a,props:n}),[ne,re]=Vt({value:u,defaultValue:d,finalValue:``,onChange:c}),ie=P!==void 0&&N!==void 0,ae=(0,b.useRef)(null),oe=(0,b.useRef)(null),se=(0,b.useRef)(0),H=(e,t)=>{t.source===`event`&&re(Sh(e.floatValue,e.value)&&!hh.test(e.value)&&!(F&&gh.test(e.value))&&!_h.test(e.value)&&!vh.test(e.value)?e.floatValue:e.value),l?.(e,t)},ce=e=>{let t=String(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0},le=e=>{ae.current&&e!==void 0&&ae.current.setSelectionRange(e,e)},ue=(0,b.useRef)(et);ue.current=()=>{if(!bh(ne))return;let e,t=ce(ne),n=ce(m),r=Math.max(t,n),i=10**r;if(!yh(ne)&&(typeof ne!=`number`||Number.isNaN(ne)))e=ut(E,p,f);else if(f!==void 0){let t=(Math.round(Number(ne)*i)+Math.round(m*i))/i;e=t<=f?t:f}else e=(Math.round(Number(ne)*i)+Math.round(m*i))/i;let a=e.toFixed(r);re(parseFloat(a)),l?.({floatValue:parseFloat(a),formattedValue:a,value:a},{source:`increment`}),setTimeout(()=>le(ae.current?.value.length),0)};let U=(0,b.useRef)(et);U.current=()=>{if(!bh(ne))return;let e,t=p===void 0?k?-(2**53-1):0:p,n=ce(ne),r=ce(m),i=Math.max(n,r),a=10**i;if(!yh(ne)&&typeof ne!=`number`||Number.isNaN(ne))e=ut(E,t,f);else{let n=(Math.round(Number(ne)*a)-Math.round(m*a))/a;e=t!==void 0&&n<t?t:n}let o=e.toFixed(i);re(parseFloat(o)),l?.({floatValue:parseFloat(o),formattedValue:o,value:o},{source:`decrement`}),setTimeout(()=>le(ae.current?.value.length),0)};let de=e=>{let t=e.clipboardData.getData(`text`),n=B.decimalSeparator||`.`,r=(R||[`.`,`,`]).filter(e=>e!==n);if(r.some(e=>t.includes(e))){e.preventDefault();let i=t;r.forEach(e=>{i=i.split(e).join(n)});let a=ae.current;if(a){let e=a.selectionStart??0,t=a.selectionEnd??0,n=a.value,r=n.substring(0,e)+i+n.substring(t);(Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,`value`)?.set)?.call(a,r),a.dispatchEvent(new Event(`change`,{bubbles:!0}));let o=e+i.length;setTimeout(()=>le(o),0)}}B.onPaste?.(e)},fe=e=>{C?.(e),!(A||!I)&&(e.key===`ArrowUp`&&(e.preventDefault(),ue.current?.()),e.key===`ArrowDown`&&(e.preventDefault(),U.current?.()))},pe=e=>{if(w?.(e),e.key===`Backspace`){let t=ae.current;t&&t.selectionStart===0&&t.selectionStart===t.selectionEnd&&(e.preventDefault(),window.setTimeout(()=>le(0),0))}},me=e=>{let t=ne;v===`blur`&&typeof t==`number`&&(t=ut(t,p,f)),L&&typeof t==`string`&&ce(t)<15&&(t=Eh(t,f,p)),ne!==t&&re(t),y?.(e)};It(T,{increment:ue.current,decrement:U.current});let he=e=>{e?ue.current?.():U.current?.(),se.current+=1},ge=e=>{if(he(e),ie){let t=typeof N==`number`?N:N(se.current);oe.current=window.setTimeout(()=>ge(e),t)}},_e=(e,t)=>{e.preventDefault(),ae.current?.focus(),he(t),ie&&(oe.current=window.setTimeout(()=>ge(t),P))},ve=()=>{oe.current&&window.clearTimeout(oe.current),oe.current=null,se.current=0},ye=(0,G.jsxs)(`div`,{...V(`controls`),children:[(0,G.jsx)(Gc,{...V(`control`),tabIndex:-1,"aria-hidden":!0,disabled:D||typeof ne==`number`&&f!==void 0&&ne>=f,mod:{direction:`up`},onMouseDown:e=>e.preventDefault(),onPointerDown:e=>{_e(e,!0)},onPointerUp:ve,onPointerLeave:ve,children:(0,G.jsx)(mh,{direction:`up`})}),(0,G.jsx)(Gc,{...V(`control`),tabIndex:-1,"aria-hidden":!0,disabled:D||typeof ne==`number`&&p!==void 0&&ne<=p,mod:{direction:`down`},onMouseDown:e=>e.preventDefault(),onPointerDown:e=>{_e(e,!1)},onPointerUp:ve,onPointerLeave:ve,children:(0,G.jsx)(mh,{direction:`down`})})]});return(0,G.jsx)(Vu,{component:fh,allowNegative:k,className:nn(ph.root,r),size:j,inputMode:`decimal`,...B,readOnly:A,disabled:D,value:ne,getInputRef:Rt(t,ae),onValueChange:H,rightSection:h||A||!bh(ne)?g:g||ye,classNames:ee,styles:te,unstyled:o,__staticSelector:`NumberInput`,decimalScale:x?S:0,onPaste:de,onKeyDown:fe,onKeyDownCapture:pe,rightSectionPointerEvents:O??(D?`none`:void 0),rightSectionWidth:M??`var(--ni-right-section-width-${j||`sm`})`,allowLeadingZeros:F,allowedDecimalSeparators:R,onBlur:me,attributes:z,isAllowed:e=>v===`strict`?_?_(e)&&Ch(e.floatValue,p,f):Ch(e.floatValue,p,f):_?_(e):!0})});Dh.classes={...Vu.classes,...ph},Dh.displayName=`@mantine/core/NumberInput`;var Oh={duration:100,transition:`fade`};function kh(e,t){return{...Oh,...t,...e}}var Ah={tooltip:`m_1b3c8819`,arrow:`m_f898399f`};function jh({offset:e,position:t,defaultOpened:n}){let[r,i]=(0,b.useState)(n),a=(0,b.useRef)(null),{x:o,y:s,elements:c,refs:l,update:u,placement:d}=tc({placement:t,middleware:[ds({crossAxis:!0,padding:5,rootBoundary:`document`})]}),f=d.includes(`right`)?e:t.includes(`left`)?e*-1:0,p=d.includes(`bottom`)?e:t.includes(`top`)?e*-1:0,m=(0,b.useCallback)(({clientX:e,clientY:t})=>{l.setPositionReference({getBoundingClientRect(){return{width:0,height:0,x:e,y:t,left:e+f,top:t+p,right:e,bottom:t}}})},[c.reference]);return(0,b.useEffect)(()=>{if(l.floating.current){let e=a.current;e.addEventListener(`mousemove`,m);let t=$i(l.floating.current);return t.forEach(e=>{e.addEventListener(`scroll`,u)}),()=>{e.removeEventListener(`mousemove`,m),t.forEach(e=>{e.removeEventListener(`scroll`,u)})}}},[c.reference,l.floating.current,u,m,r]),{handleMouseMove:m,x:o,y:s,opened:r,setOpened:i,boundaryRef:a,floating:l.setFloating}}var Mh={refProp:`ref`,withinPortal:!0,offset:10,position:`right`,zIndex:$e(`popover`)},Nh=en((e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:it(t),"--tooltip-bg":n?An(n,e):void 0,"--tooltip-color":n?`var(--mantine-color-white)`:void 0}})),Ph=_i((e,t)=>{let n=K(`TooltipFloating`,Mh,e),{children:r,refProp:i,withinPortal:a,style:o,className:s,classNames:c,styles:l,unstyled:u,radius:d,color:f,label:p,offset:m,position:h,multiline:g,zIndex:_,disabled:v,defaultOpened:y,variant:x,vars:S,portalProps:C,attributes:w,...T}=n,E=qn(),D=jr({name:`TooltipFloating`,props:n,classes:Ah,className:s,style:o,classNames:c,styles:l,unstyled:u,attributes:w,rootSelector:`tooltip`,vars:S,varsResolver:Nh}),{handleMouseMove:O,x:k,y:A,opened:j,boundaryRef:M,floating:N,setOpened:P}=jh({offset:m,position:h,defaultOpened:y}),F=$t(r);if(!F)throw Error(`[@mantine/core] Tooltip.Floating component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported`);let I=Rt(M,Yt(F),t),L=F.props,R=e=>{L.onMouseEnter?.(e),O(e),P(!0)},z=e=>{L.onMouseLeave?.(e),P(!1)};return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(dl,{...C,withinPortal:a,children:(0,G.jsx)(q,{...T,...D(`tooltip`,{style:{...si(o,E),zIndex:_,display:!v&&j?`block`:`none`,top:(A&&Math.round(A))??``,left:(k&&Math.round(k))??``}}),variant:x,ref:N,mod:{multiline:g},children:p})}),(0,b.cloneElement)(F,{...L,[i]:I,onMouseEnter:R,onMouseLeave:z})]})});Ph.classes=Ah,Ph.displayName=`@mantine/core/TooltipFloating`;var Fh=(0,b.createContext)(!1),Ih=Fh.Provider,Lh=()=>(0,b.useContext)(Fh),Rh={openDelay:0,closeDelay:0};function zh(e){let{openDelay:t,closeDelay:n,children:r}=K(`TooltipGroup`,Rh,e);return(0,G.jsx)(Ih,{value:!0,children:(0,G.jsx)(Js,{delay:{open:t,close:n},children:r})})}zh.displayName=`@mantine/core/TooltipGroup`,zh.extend=e=>e;function Bh(e){if(e===void 0)return{shift:!0,flip:!0};let t={...e};return e.shift===void 0&&(t.shift=!0),e.flip===void 0&&(t.flip=!0),t}function Vh(e){let t=Bh(e.middlewares),n=[us(e.offset)];return t.shift&&n.push(ds(typeof t.shift==`boolean`?{padding:8}:{padding:8,...t.shift})),t.flip&&n.push(typeof t.flip==`boolean`?ps():ps(t.flip)),n.push(_s({element:e.arrowRef,padding:e.arrowOffset})),t.inline?n.push(typeof t.inline==`boolean`?gs():gs(t.inline)):e.inline&&n.push(gs()),n}function Hh(e){let[t,n]=(0,b.useState)(e.defaultOpened),r=typeof e.opened==`boolean`?e.opened:t,i=Lh(),a=Pt(),o=(0,b.useCallback)(e=>{n(e),e&&g(a)},[a]),{x:s,y:c,context:l,refs:u,placement:d,middlewareData:{arrow:{x:f,y:p}={}}}=tc({strategy:e.strategy,placement:e.position,open:r,onOpenChange:o,middleware:Vh(e),whileElementsMounted:qo}),{delay:m,currentId:h,setCurrentId:g}=Ys(l,{id:a}),{getReferenceProps:_,getFloatingProps:v}=ac([Ws(l,{enabled:e.events?.hover,delay:i?m:{open:e.openDelay,close:e.closeDelay},mouseOnly:!e.events?.touch}),rc(l,{enabled:e.events?.focus,visibleOnly:!0}),sc(l,{role:`tooltip`}),$s(l,{enabled:e.opened===void 0})]);bt(()=>{e.onPositionChange?.(d)},[d]);let y=r&&h&&h!==a;return{x:s,y:c,arrowX:f,arrowY:p,reference:u.setReference,floating:u.setFloating,getFloatingProps:v,getReferenceProps:_,isGroupPhase:y,opened:r,placement:d}}var Uh={position:`top`,refProp:`ref`,withinPortal:!0,arrowSize:4,arrowOffset:5,arrowRadius:0,arrowPosition:`side`,offset:5,transitionProps:{duration:100,transition:`fade`},events:{hover:!0,focus:!1,touch:!1},zIndex:$e(`popover`),positionDependencies:[],middlewares:{flip:!0,shift:!0,inline:!1}},Wh=en((e,{radius:t,color:n,variant:r,autoContrast:i})=>{let a=e.variantColorResolver({theme:e,color:n||e.primaryColor,autoContrast:i,variant:r||`filled`});return{tooltip:{"--tooltip-radius":t===void 0?void 0:it(t),"--tooltip-bg":n?a.background:void 0,"--tooltip-color":n?a.color:void 0}}}),Gh=_i((e,t)=>{let n=K(`Tooltip`,Uh,e),{children:r,position:i,refProp:a,label:o,openDelay:s,closeDelay:c,onPositionChange:l,opened:u,defaultOpened:d,withinPortal:f,radius:p,color:m,classNames:h,styles:g,unstyled:_,style:v,className:y,withArrow:x,arrowSize:S,arrowOffset:C,arrowRadius:w,arrowPosition:T,offset:E,transitionProps:D,multiline:O,events:k,zIndex:A,disabled:j,positionDependencies:M,onClick:N,onMouseEnter:P,onMouseLeave:F,inline:I,variant:L,keepMounted:R,vars:z,portalProps:B,mod:V,floatingStrategy:ee,middlewares:te,autoContrast:ne,attributes:re,target:ie,...ae}=K(`Tooltip`,Uh,n),{dir:oe}=bi(),se=(0,b.useRef)(null),H=Hh({position:nl(oe,i),closeDelay:c,openDelay:s,onPositionChange:l,opened:u,defaultOpened:d,events:k,arrowRef:se,arrowOffset:C,offset:typeof E==`number`?E+(x?S/2:0):E,positionDependencies:[...M,ie??r],inline:I,strategy:ee,middlewares:te});(0,b.useEffect)(()=>{let e=ie instanceof HTMLElement?ie:typeof ie==`string`?document.querySelector(ie):ie?.current||null;e&&H.reference(e)},[ie,H]);let ce=jr({name:`Tooltip`,props:n,classes:Ah,className:y,style:v,classNames:h,styles:g,unstyled:_,attributes:re,rootSelector:`tooltip`,vars:z,varsResolver:Wh}),le=$t(r);if(!ie&&!le)throw Error(`[@mantine/core] Tooltip component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported`);if(ie){let e=kh(D,{duration:100,transition:`fade`});return(0,G.jsx)(G.Fragment,{children:(0,G.jsx)(dl,{...B,withinPortal:f,children:(0,G.jsx)(_l,{...e,keepMounted:R,mounted:!j&&!!H.opened,duration:H.isGroupPhase?10:e.duration,children:e=>(0,G.jsxs)(q,{...ae,"data-fixed":ee===`fixed`||void 0,variant:L,mod:[{multiline:O},V],...H.getFloatingProps({ref:H.floating,className:ce(`tooltip`).className,style:{...ce(`tooltip`).style,...e,zIndex:A,top:H.y??0,left:H.x??0}}),children:[o,(0,G.jsx)(tl,{ref:se,arrowX:H.arrowX,arrowY:H.arrowY,visible:x,position:H.placement,arrowSize:S,arrowOffset:C,arrowRadius:w,arrowPosition:T,...ce(`arrow`)})]})})})})}let ue=le.props,U=Rt(H.reference,Yt(le),t),de=kh(D,{duration:100,transition:`fade`});return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(dl,{...B,withinPortal:f,children:(0,G.jsx)(_l,{...de,keepMounted:R,mounted:!j&&!!H.opened,duration:H.isGroupPhase?10:de.duration,children:e=>(0,G.jsxs)(q,{...ae,"data-fixed":ee===`fixed`||void 0,variant:L,mod:[{multiline:O},V],...H.getFloatingProps({ref:H.floating,className:ce(`tooltip`).className,style:{...ce(`tooltip`).style,...e,zIndex:A,top:H.y??0,left:H.x??0}}),children:[o,(0,G.jsx)(tl,{ref:se,arrowX:H.arrowX,arrowY:H.arrowY,visible:x,position:H.placement,arrowSize:S,arrowOffset:C,arrowRadius:w,arrowPosition:T,...ce(`arrow`)})]})})}),(0,b.cloneElement)(le,H.getReferenceProps({onClick:N,onMouseEnter:P,onMouseLeave:F,onMouseMove:n.onMouseMove,onPointerDown:n.onPointerDown,onPointerEnter:n.onPointerEnter,...ue,className:nn(y,ue.className),[a]:U}))]})});Gh.classes=Ah,Gh.displayName=`@mantine/core/Tooltip`,Gh.Floating=Ph,Gh.Group=zh;var Kh={withCheckIcon:!0,allowDeselect:!0,checkIconPosition:`left`,openOnFocus:!0},qh=_i((e,t)=>{let n=K(`Select`,Kh,e),{classNames:r,styles:i,unstyled:a,vars:o,dropdownOpened:s,defaultDropdownOpened:c,onDropdownClose:l,onDropdownOpen:u,onFocus:d,onBlur:f,onClick:p,onChange:m,data:h,value:g,defaultValue:_,selectFirstOptionOnChange:v,selectFirstOptionOnDropdownOpen:y,onOptionSubmit:x,comboboxProps:S,readOnly:C,disabled:w,filter:T,limit:E,withScrollArea:D,maxDropdownHeight:O,size:k,searchable:A,rightSection:j,checkIconPosition:M,withCheckIcon:N,withAlignedLabels:P,nothingFoundMessage:F,name:I,form:L,searchValue:R,defaultSearchValue:z,onSearchChange:B,allowDeselect:V,error:ee,rightSectionPointerEvents:te,id:ne,clearable:re,clearButtonProps:ie,hiddenInputProps:ae,renderOption:oe,onClear:se,autoComplete:H,scrollAreaProps:ce,__defaultRightSection:le,__clearSection:ue,__clearable:U,chevronColor:de,autoSelectOnBlur:fe,openOnFocus:pe,attributes:me,...he}=n,ge=(0,b.useMemo)(()=>nd(h),[h]),_e=(0,b.useRef)({}),ve=(0,b.useMemo)(()=>rd(ge),[ge]),ye=Pt(ne),[be,xe,Se]=Vt({value:g,defaultValue:_,finalValue:null,onChange:m}),Ce=typeof be==`string`?be in ve?ve[be]:_e.current[be]:void 0,we=Wt(Ce),[Te,Ee,De]=Vt({value:R,defaultValue:z,finalValue:Ce?Ce.label:``,onChange:B}),Oe=jd({opened:s,defaultOpened:c,onDropdownOpen:()=>{u?.(),y?Oe.selectFirstOption():Oe.updateSelectedOptionIndex(`active`,{scrollIntoView:!0})},onDropdownClose:()=>{l?.(),setTimeout(Oe.resetSelectedOption,0)}}),ke=e=>{Ee(e),Oe.resetSelectedOption()},{resolvedClassNames:Ae,resolvedStyles:je}=mr({props:n,styles:i,classNames:r});(0,b.useEffect)(()=>{v&&Oe.selectFirstOption()},[v,Te]),(0,b.useEffect)(()=>{g===null&&ke(``),typeof g==`string`&&Ce&&(we?.value!==Ce.value||we?.label!==Ce.label)&&ke(Ce.label)},[g,Ce]),(0,b.useEffect)(()=>{!Se&&!De&&ke(typeof be==`string`?be in ve?ve[be]?.label:_e.current[be]?.label||``:``)},[ve,be]),(0,b.useEffect)(()=>{be&&be in ve&&(_e.current[be]=ve[be])},[ve,be]);let Me=(0,G.jsx)(Pd.ClearButton,{...ie,onClear:()=>{xe(null,null),ke(``),se?.()}}),Ne=re&&!!be&&!w&&!C;return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(Pd,{store:Oe,__staticSelector:`Select`,classNames:Ae,styles:je,unstyled:a,readOnly:C,size:k,attributes:me,keepMounted:fe,onOptionSubmit:e=>{x?.(e);let t=V&&ve[e].value===be?null:ve[e],n=t?t.value:null;n!==be&&xe(n,t),!Se&&ke(typeof n==`string`&&t?.label||``),Oe.closeDropdown()},...S,children:[(0,G.jsx)(Pd.Target,{targetType:A?`input`:`button`,autoComplete:H,children:(0,G.jsx)(Vu,{id:ye,ref:t,__defaultRightSection:(0,G.jsx)(Pd.Chevron,{size:k,error:ee,unstyled:a,color:de}),__clearSection:Me,__clearable:Ne,rightSection:j,rightSectionPointerEvents:te||`none`,...he,size:k,__staticSelector:`Select`,disabled:w,readOnly:C||!A,value:Te,onChange:e=>{ke(e.currentTarget.value),Oe.openDropdown(),v&&Oe.selectFirstOption()},onFocus:e=>{pe&&A&&Oe.openDropdown(),d?.(e)},onBlur:e=>{fe&&Oe.clickSelectedOption(),A&&Oe.closeDropdown();let t=typeof be==`string`&&(be in ve?ve[be]:_e.current[be]);ke(t&&t.label||``),f?.(e)},onClick:e=>{A?Oe.openDropdown():Oe.toggleDropdown(),p?.(e)},classNames:Ae,styles:je,unstyled:a,pointer:!A,error:ee,attributes:me})}),(0,G.jsx)(ff,{data:ge,hidden:C||w,filter:T,search:Te,limit:E,hiddenWhenEmpty:!F,withScrollArea:D,maxDropdownHeight:O,filterOptions:!!A&&Ce?.label!==Te,value:be,checkIconPosition:M,withCheckIcon:N,withAlignedLabels:P,nothingFoundMessage:F,unstyled:a,labelId:he.label?`${ye}-label`:void 0,"aria-label":he.label?void 0:he[`aria-label`],renderOption:oe,scrollAreaProps:ce})]}),(0,G.jsx)(Pd.HiddenInput,{value:be,name:I,form:L,disabled:w,...ae})]})});qh.classes={...Vu.classes,...Pd.classes},qh.displayName=`@mantine/core/Select`;var[Jh,Yh]=Ge(`SliderProvider was not found in tree`),Xh={root:`m_dd36362e`,label:`m_c9357328`,thumb:`m_c9a9a60a`,trackContainer:`m_a8645c2`,track:`m_c9ade57f`,bar:`m_38aeed47`,markWrapper:`m_b7b0423a`,mark:`m_dd33bc19`,markLabel:`m_68c77a5b`},Zh=(0,b.forwardRef)(({size:e,disabled:t,variant:n,color:r,thumbSize:i,radius:a,...o},s)=>{let{getStyles:c}=Yh();return(0,G.jsx)(q,{tabIndex:-1,variant:n,size:e,ref:s,...c(`root`),...o})});Zh.displayName=`@mantine/core/SliderRoot`;var Qh=(0,b.forwardRef)(({max:e,min:t,value:n,position:r,label:i,dragging:a,onMouseDown:o,onKeyDownCapture:s,labelTransitionProps:c,labelAlwaysOn:l,thumbLabel:u,onFocus:d,onBlur:f,showLabelOnHover:p,isHovered:m,children:h=null,disabled:g},_)=>{let{getStyles:v}=Yh(),[y,x]=(0,b.useState)(!1),S=l||a||y||p&&m;return(0,G.jsxs)(q,{tabIndex:0,role:`slider`,"aria-label":u,"aria-valuemax":e,"aria-valuemin":t,"aria-valuenow":n,ref:_,__vars:{"--slider-thumb-offset":`${r}%`},...v(`thumb`,{focusable:!0}),mod:{dragging:a,disabled:g},onFocus:e=>{x(!0),typeof d==`function`&&d(e)},onBlur:e=>{x(!1),typeof f==`function`&&f(e)},onTouchStart:o,onMouseDown:o,onKeyDownCapture:s,onClick:e=>e.stopPropagation(),children:[h,(0,G.jsx)(_l,{mounted:i!=null&&!!S,transition:`fade`,duration:0,...c,children:e=>(0,G.jsx)(`div`,{...v(`label`,{style:e}),children:i})})]})});Qh.displayName=`@mantine/core/SliderThumb`;function $h({value:e,min:t,max:n}){let r=(e-t)/(n-t)*100;return Math.min(Math.max(r,0),100)}function eg({mark:e,offset:t,value:n,inverted:r=!1}){return r?typeof t==`number`&&e.value<=t||e.value>=n:typeof t==`number`?e.value>=t&&e.value<=n:e.value<=n}function tg({marks:e,min:t,max:n,disabled:r,value:i,offset:a,inverted:o}){let{getStyles:s}=Yh();return e?(0,G.jsx)(`div`,{children:e.map((e,c)=>(0,b.createElement)(q,{...s(`markWrapper`),__vars:{"--mark-offset":`${$h({value:e.value,min:t,max:n})}%`},key:c},(0,G.jsx)(q,{...s(`mark`),mod:{filled:eg({mark:e,value:i,offset:a,inverted:o}),disabled:r}}),e.label&&(0,G.jsx)(`div`,{...s(`markLabel`),children:e.label})))}):null}tg.displayName=`@mantine/core/SliderMarks`;function ng({filled:e,children:t,offset:n,disabled:r,marksOffset:i,inverted:a,containerProps:o,...s}){let{getStyles:c}=Yh();return(0,G.jsx)(q,{...c(`trackContainer`),mod:{disabled:r},...o,children:(0,G.jsxs)(q,{...c(`track`),mod:{inverted:a,disabled:r},children:[(0,G.jsx)(q,{mod:{inverted:a,disabled:r},__vars:{"--slider-bar-width":`calc(${e}% + 2 * var(--slider-size))`,"--slider-bar-offset":`calc(${n}% - var(--slider-size))`},...c(`bar`)}),t,(0,G.jsx)(tg,{...s,offset:i,disabled:r,inverted:a})]})})}ng.displayName=`@mantine/core/SliderTrack`;function rg({value:e,containerWidth:t,min:n,max:r,step:i,precision:a}){let o=(t?Math.min(Math.max(e,0),t)/t:e)*(r-n),s=(o===0?0:Math.round(o/i)*i)+n,c=Math.max(s,n);return a===void 0?c:Number(c.toFixed(a))}function ig(e,t){return parseFloat(e.toFixed(t))}function ag(e){if(!e)return 0;let t=e.toString().split(`.`);return t.length>1?t[1].length:0}function og(e,t){let n=[...t].sort((e,t)=>e.value-t.value).find(t=>t.value>e);return n?n.value:e}function sg(e,t){let n=[...t].sort((e,t)=>t.value-e.value).find(t=>t.value<e);return n?n.value:e}function cg(e){let t=[...e].sort((e,t)=>e.value-t.value);return t.length>0?t[0].value:0}function lg(e){let t=[...e].sort((e,t)=>e.value-t.value);return t.length>0?t[t.length-1].value:100}var ug={radius:`xl`,min:0,max:100,step:1,marks:[],label:e=>e,labelTransitionProps:{transition:`fade`,duration:0},thumbLabel:``,showLabelOnHover:!0,scale:e=>e,size:`md`},dg=en((e,{size:t,color:n,thumbSize:r,radius:i})=>({root:{"--slider-size":nt(t,`slider-size`),"--slider-color":n?An(n,e):void 0,"--slider-radius":i===void 0?void 0:it(i),"--slider-thumb-size":r===void 0?`calc(var(--slider-size) * 2)`:W(r)}})),fg=_i((e,t)=>{let n=K(`Slider`,ug,e),{classNames:r,styles:i,value:a,onChange:o,onChangeEnd:s,size:c,min:l,max:u,domain:d,step:f,precision:p,defaultValue:m,name:h,marks:g,label:_,labelTransitionProps:v,labelAlwaysOn:y,thumbLabel:x,showLabelOnHover:S,thumbChildren:C,disabled:w,unstyled:T,scale:E,inverted:D,className:O,style:k,vars:A,hiddenInputProps:j,restrictToMarks:M,thumbProps:N,attributes:P,...F}=n,I=jr({name:`Slider`,props:n,classes:Xh,classNames:r,className:O,styles:i,style:k,attributes:P,vars:A,varsResolver:dg,unstyled:T}),{dir:L}=bi(),[R,z]=(0,b.useState)(!1),[B,V]=Vt({value:typeof a==`number`?ut(a,l,u):a,defaultValue:typeof m==`number`?ut(m,l,u):m,finalValue:ut(0,l,u),onChange:o}),ee=(0,b.useRef)(B),te=(0,b.useRef)(s);(0,b.useEffect)(()=>{te.current=s},[s]);let ne=(0,b.useRef)(null),re=(0,b.useRef)(null),[ie,ae]=d||[l,u],oe=$h({value:B,min:ie,max:ae}),se=E(B),H=typeof _==`function`?_(se):_,ce=p??ag(f),{ref:le,active:ue}=Bt((0,b.useCallback)(({x:e})=>{if(!w){let t=ut(rg({value:e,min:ie,max:ae,step:f,precision:ce}),l,u);V(M&&g?.length?Jt(t,g.map(e=>e.value)):t),ee.current=t}},[w,l,u,ie,ae,f,ce,V,g,M]),{onScrubEnd:(0,b.useCallback)(()=>{if(!w&&te.current){let e=M&&g?.length?Jt(ee.current,g.map(e=>e.value)):ee.current;te.current(e)}},[w,g,M])},L),U=(0,b.useCallback)(e=>{!w&&te.current&&te.current(e)},[w]),de=e=>{if(!w)switch(e.key){case`ArrowUp`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=og(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(B+f,l),u),ce);V(t),U(t);break}case`ArrowRight`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=L===`rtl`?sg(B,g):og(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(L===`rtl`?B-f:B+f,l),u),ce);V(t),U(t);break}case`ArrowDown`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=sg(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(B-f,l),u),ce);V(t),U(t);break}case`ArrowLeft`:{if(e.preventDefault(),re.current?.focus(),M&&g){let e=L===`rtl`?og(B,g):sg(B,g);V(e),U(e);break}let t=ig(Math.min(Math.max(L===`rtl`?B+f:B-f,l),u),ce);V(t),U(t);break}case`Home`:if(e.preventDefault(),re.current?.focus(),M&&g){V(cg(g)),U(cg(g));break}V(l),U(l);break;case`End`:if(e.preventDefault(),re.current?.focus(),M&&g){V(lg(g)),U(lg(g));break}V(u),U(u);break}};return(0,G.jsx)(Jh,{value:{getStyles:I},children:(0,G.jsxs)(Zh,{...F,ref:Rt(t,ne),onKeyDownCapture:de,onMouseDownCapture:()=>ne.current?.focus(),size:c,disabled:w,children:[(0,G.jsx)(ng,{inverted:D,offset:0,filled:oe,marks:g,min:ie,max:ae,value:se,disabled:w,containerProps:{ref:le,onMouseEnter:S?()=>z(!0):void 0,onMouseLeave:S?()=>z(!1):void 0},children:(0,G.jsx)(Qh,{max:ae,min:ie,value:se,position:oe,dragging:ue,label:H,ref:re,labelTransitionProps:v,labelAlwaysOn:y,thumbLabel:x,showLabelOnHover:S,isHovered:R,disabled:w,...N,children:C})}),(0,G.jsx)(`input`,{type:`hidden`,name:h,value:se,...j})]})})});fg.classes=Xh,fg.displayName=`@mantine/core/Slider`;var pg={root:`m_6d731127`},mg={gap:`md`,align:`stretch`,justify:`flex-start`},hg=en((e,{gap:t,align:n,justify:r})=>({root:{"--stack-gap":rt(t),"--stack-align":n,"--stack-justify":r}})),gg=_i((e,t)=>{let n=K(`Stack`,mg,e),{classNames:r,className:i,style:a,styles:o,unstyled:s,vars:c,align:l,justify:u,gap:d,variant:f,attributes:p,...m}=n;return(0,G.jsx)(q,{ref:t,...jr({name:`Stack`,props:n,classes:pg,className:i,style:a,classNames:r,styles:o,unstyled:s,attributes:p,vars:c,varsResolver:hg})(`root`),variant:f,...m})});gg.classes=pg,gg.displayName=`@mantine/core/Stack`;var _g=_i((e,t)=>(0,G.jsx)(Vu,{component:`input`,ref:t,...K(`TextInput`,null,e),__staticSelector:`TextInput`}));_g.classes=Vu.classes,_g.displayName=`@mantine/core/TextInput`;var vg={outline:{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`},filled:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`currentColor`,stroke:`none`}},yg=(e,t,n,r)=>{let i=(0,b.forwardRef)(({color:n=`currentColor`,size:i=24,stroke:a=2,title:o,className:s,children:c,...l},u)=>(0,b.createElement)(`svg`,{ref:u,...vg[e],width:i,height:i,className:[`tabler-icon`,`tabler-icon-${t}`,s].join(` `),...e===`filled`?{fill:n}:{strokeWidth:a,stroke:n},...l},[o&&(0,b.createElement)(`title`,{key:`svg-title`},o),...r.map(([e,t])=>(0,b.createElement)(e,t)),...Array.isArray(c)?c:[c]]));return i.displayName=`${n}`,i},bg=yg(`outline`,`chevron-down`,`ChevronDown`,[[`path`,{d:`M6 9l6 6l6 -6`,key:`svg-0`}]]),xg=yg(`outline`,`chevron-up`,`ChevronUp`,[[`path`,{d:`M6 15l6 -6l6 6`,key:`svg-0`}]]),Sg=yg(`outline`,`refresh`,`Refresh`,[[`path`,{d:`M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4`,key:`svg-0`}],[`path`,{d:`M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4`,key:`svg-1`}]]),Cg=yg(`outline`,`x`,`X`,[[`path`,{d:`M18 6l-12 12`,key:`svg-0`}],[`path`,{d:`M6 6l12 12`,key:`svg-1`}]]),wg=d(),Tg=`0.8.2`,Eg=[{login:`ttktjmt`,html_url:`https://github.com/ttktjmt`},{login:`claude`,html_url:`https://github.com/claude`},{login:`Axellwppr`,html_url:`https://github.com/Axellwppr`},{login:`julien-blanchon`,html_url:`https://github.com/julien-blanchon`},{login:`unmoyai`,html_url:`https://github.com/unmoyai`},{login:`brentyi`,html_url:`https://github.com/brentyi`},{login:`CharlieLeee`,html_url:`https://github.com/CharlieLeee`}],Dg={move:`touchmove`,end:`touchend`},Og={move:`mousemove`,end:`mouseup`};function kg(e){return e.type===`touchmove`}function Ag(e){return e.type===`mousemove`}var jg=b.createContext(null);function Mg({children:e,width:t,visible:n=!0,onVisibleChange:r,hiddenButtonTooltip:i}){let a=b.useRef(null),[o,{toggle:s}]=Ut(!0),[c,l]=b.useState(800),u=b.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),d=b.useRef({}),f=(e,t,n)=>Math.abs(e+t/2)<Math.abs(e-n+t/2)?e:e-n;function p(e,t){let n=a.current;if(n===null)return[e,t];let r=n.parentElement;if(r===null)return[e,t];let i=e,o=t;return i=Math.min(i,r.clientWidth-n.clientWidth-15),i=Math.max(i,15),o=Math.min(o,r.clientHeight-n.clientHeight-15),o=Math.max(o,15),n.style.top=`${o.toString()}px`,n.style.left=`${i.toString()}px`,[f(i,n.clientWidth,r.clientWidth),f(o,n.clientHeight,r.clientHeight)]}b.useEffect(()=>{let e=a.current;if(e===null)return;let t=e.parentElement;if(t===null)return;let n=new ResizeObserver(()=>{d.current.x===void 0&&(d.current.x=f(e.offsetLeft,e.clientWidth,t.clientWidth)),d.current.y===void 0&&(d.current.y=f(e.offsetTop,e.clientHeight,t.clientHeight));let n=t.clientHeight-30;c!==n&&l(n);let r=d.current.x,i=d.current.y;for(;r<0;)r+=t.clientWidth;for(;i<0;)i+=t.clientHeight;p(r,i)});return n.observe(e),n.observe(t),()=>{n.disconnect()}});let m=e=>{let t=u.current,n=a.current;if(!n)return;e.type==`touchstart`?(e=e,t.startClientX=e.touches[0].clientX,t.startClientY=e.touches[0].clientY):(e=e,t.startClientX=e.clientX,t.startClientY=e.clientY),t.startPosX=n.offsetLeft,t.startPosY=n.offsetTop;let r=e.type==`touchstart`?Dg:Og;function i(e){let n=0,r=0;if(kg(e)?(e=e,n=e.touches[0].clientX-t.startClientX,r=e.touches[0].clientY-t.startClientY):Ag(e)&&(e=e,n=e.clientX-t.startClientX,r=e.clientY-t.startClientY),Math.abs(n)<=3&&Math.abs(r)<=3)return;t.dragging=!0;let i=t.startPosX+n,a=t.startPosY+r;[d.current.x,d.current.y]=p(i,a)}window.addEventListener(r.move,i),window.addEventListener(r.end,()=>{e.type==`touchstart`&&(t.dragging=!1),window.removeEventListener(r.move,i)},{once:!0})};if(!n){let e=(0,G.jsx)(q,{component:`button`,"aria-label":i??`Show controls`,onClick:()=>r?.(!0),style:{width:`0.85rem`,height:`0.85rem`,minWidth:`0.85rem`,minHeight:`0.85rem`,display:`block`,padding:0,border:`none`,borderRadius:`9999px`,background:`rgba(255, 255, 255, 0.82)`,boxShadow:`0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)`,cursor:`pointer`}});return(0,G.jsx)(q,{style:{zIndex:10,position:`absolute`,top:`1em`,right:`1em`},children:i?(0,G.jsx)(Gh,{label:i,children:(0,G.jsx)(q,{children:e})}):e})}return(0,G.jsx)(jg.Provider,{value:{wrapperRef:a,expanded:o,width:t,maxHeight:c,toggleExpanded:s,dragHandler:m,dragInfo:u},children:(0,G.jsx)(Xc,{radius:`xs`,shadow:`0.1em 0 1em 0 rgba(0,0,0,0.1)`,style:{boxSizing:`border-box`,width:t,zIndex:10,position:`absolute`,top:`1em`,right:`1em`,margin:0,"& .expandIcon":{transform:`rotate(0)`},overflow:`hidden`},ref:a,children:e})})}Mg.Handle=function({children:e}){let t=b.useContext(jg);return(0,G.jsx)(G.Fragment,{children:(0,G.jsx)(q,{style:{borderRadius:`0.2em 0.2em 0 0`,lineHeight:`1.5em`,cursor:`pointer`,position:`relative`,fontWeight:400,userSelect:`none`,display:`flex`,alignItems:`center`,padding:`0 0.75em`,height:`2.75em`},onClick:()=>{let e=t.dragInfo.current;if(e.dragging){e.dragging=!1;return}t.toggleExpanded()},onTouchStart:e=>{t.dragHandler(e)},onMouseDown:e=>{t.dragHandler(e)},children:e})})},Mg.Contents=function({children:e}){let t=b.useContext(jg);return(0,G.jsxs)(ki,{in:t.expanded,children:[(0,G.jsx)(hp,{mx:`xs`}),(0,G.jsx)(Vc.Autosize,{mah:t.maxHeight,children:(0,G.jsx)(q,{style:{width:t.width},children:e})})]})},Mg.HideWhenCollapsed=function({children:e}){return b.useContext(jg)?.expanded??!0?e:null},Mg.HideWhenExpanded=function({children:e}){return b.useContext(jg)?.expanded??!0?null:e};function Ng({id:e,label:t,children:n}){return(0,G.jsx)(q,{pb:`0.5em`,px:`xs`,children:(0,G.jsxs)(Wu,{align:`center`,children:[(0,G.jsx)(q,{pr:`xs`,style:{width:`7.25em`,flexShrink:0,position:`relative`},children:(0,G.jsx)(Zu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`100%`,boxSizing:`content-box`},children:(0,G.jsx)(`label`,{htmlFor:e,children:t})})}),(0,G.jsx)(q,{style:{flexGrow:1},children:n})]})})}function Pg({label:e,expandByDefault:t=!0,children:n}){let[r,{toggle:i}]=Ut(t);return(0,G.jsxs)(Xc,{withBorder:!0,style:{borderWidth:`1px`,position:`relative`,marginLeft:`var(--mantine-spacing-xs)`,marginRight:`var(--mantine-spacing-xs)`,marginTop:`var(--mantine-spacing-xs)`,marginBottom:`var(--mantine-spacing-xs)`,paddingBottom:`calc(var(--mantine-spacing-xs) - 0.5em)`},children:[(0,G.jsxs)(Xc,{onClick:i,style:{fontSize:`0.875em`,position:`absolute`,padding:`0 0.375em`,top:0,left:`0.375em`,transform:`translateY(-50%)`,userSelect:`none`,fontWeight:500,cursor:`pointer`,display:`flex`,alignItems:`center`},children:[e,(0,G.jsx)(r?xg:bg,{style:{width:`0.9em`,height:`0.9em`,strokeWidth:3,top:`0.1em`,position:`relative`,marginLeft:`0.25em`,marginRight:`-0.1em`,opacity:.5}})]}),(0,G.jsx)(ki,{in:r,children:(0,G.jsx)(q,{pt:`1em`,children:n})}),(0,G.jsx)(ki,{in:!r,children:(0,G.jsx)(q,{p:`xs`})})]})}var Fg={fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`4.5em`,flexShrink:0},Ig={root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}},Lg={flex:1,minWidth:0,height:`1.75em`,fontSize:`0.8em`,fontFamily:`inherit`,border:`1px solid var(--mantine-color-default-border)`,borderRadius:`var(--mantine-radius-sm)`,background:`var(--mantine-color-default)`,color:`var(--mantine-color-text)`,textAlign:`right`,padding:`0 0.4em`,outline:`none`,cursor:`ns-resize`,touchAction:`none`};function Rg({axis:e,value:t,min:n=-1/0,max:r=1/0,step:i,onChange:a}){let o=(0,b.useRef)(null),s=(0,b.useRef)(null);(0,b.useEffect)(()=>{let e=o.current;e&&document.activeElement!==e&&(e.value=t.toFixed(2))},[t]);let c=e=>Math.max(n,Math.min(r,parseFloat((Math.round(e/i)*i).toFixed(10))));return(0,G.jsxs)(q,{style:{display:`flex`,alignItems:`center`,gap:`0.25em`,flex:1},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,letterSpacing:`-0.75px`,flexShrink:0},children:e}),(0,G.jsx)(`input`,{ref:o,size:1,defaultValue:t.toFixed(2),onPointerDown:e=>{e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),s.current={startY:e.clientY,startValue:t,moved:!1}},onPointerMove:e=>{if(!s.current||!(e.buttons&1))return;let t=s.current.startY-e.clientY;if(Math.abs(t)>3&&(s.current.moved=!0),!s.current.moved)return;let n=c(s.current.startValue+t*i);a(n),o.current&&(o.current.value=n.toFixed(2))},onPointerUp:()=>{if(s.current&&!s.current.moved){let e=o.current;e&&(e.focus(),e.select())}s.current=null},onBlur:e=>{let n=parseFloat(e.target.value);isNaN(n)||a(c(n)),e.target.value=t.toFixed(2)},onKeyDown:e=>{e.key===`Enter`&&e.currentTarget.blur(),e.key===`Escape`&&(o.current&&(o.current.value=t.toFixed(2)),o.current?.blur())},onFocus:e=>e.currentTarget.style.outline=`2px solid var(--mantine-color-blue-5)`,onBlurCapture:e=>e.currentTarget.style.outline=`none`,style:Lg})]})}function zg({label:e,x:t,y:n,z:r,step:i,xLabel:a=`X`,yLabel:o=`Y`,zLabel:s=`Z`,onX:c,onY:l,onZ:u}){return(0,G.jsxs)(q,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:Fg,children:e}),(0,G.jsx)(Rg,{axis:a,value:t,step:i,onChange:c}),(0,G.jsx)(Rg,{axis:o,value:n,step:i,onChange:l}),(0,G.jsx)(Rg,{axis:s,value:r,step:i,onChange:u})]})}function Bg({scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o,onCalibrate:s}){let[c,l]=(0,b.useState)(e),[u,d]=(0,b.useState)(t),[f,p]=(0,b.useState)(n),[m,h]=(0,b.useState)(r),[g,_]=(0,b.useState)(i),[v,y]=(0,b.useState)(a),[x,S]=(0,b.useState)(o);(0,b.useEffect)(()=>{l(e)},[e]),(0,b.useEffect)(()=>{d(t)},[t]),(0,b.useEffect)(()=>{p(n)},[n]),(0,b.useEffect)(()=>{h(r)},[r]),(0,b.useEffect)(()=>{_(i)},[i]),(0,b.useEffect)(()=>{y(a)},[a]),(0,b.useEffect)(()=>{S(o)},[o]);let C=(e,t,n,r,i,a,o)=>s(e,t,n,r,i,a,o);return(0,G.jsxs)(Pg,{label:`Control`,expandByDefault:!0,children:[(0,G.jsxs)(q,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:Fg,children:`Scale`}),(0,G.jsx)(q,{style:{flex:1},children:(0,G.jsx)(fg,{value:c,onChange:e=>{l(e),C(e,u,f,m,g,v,x)},min:.1,max:5,step:.05,size:`xs`,label:e=>e.toFixed(2),styles:Ig})})]}),(0,G.jsx)(zg,{label:`Position`,x:u,y:f,z:m,step:.05,onX:e=>{d(e),C(c,e,f,m,g,v,x)},onY:e=>{p(e),C(c,u,e,m,g,v,x)},onZ:e=>{h(e),C(c,u,f,e,g,v,x)}}),(0,G.jsx)(zg,{label:`Rotation`,x:g,y:v,z:x,step:.5,xLabel:`R`,yLabel:`P`,zLabel:`Y`,onX:e=>{_(e),C(c,u,f,m,e,v,x)},onY:e=>{y(e),C(c,u,f,m,g,e,x)},onZ:e=>{S(e),C(c,u,f,m,g,v,e)}})]})}function Vg(e){return e instanceof HTMLElement?e.isContentEditable?!0:e.closest(`input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]`)!==null:!1}function Hg(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Ug({command:e,value:t,onChange:n,disabled:r,enabledWhenValue:i}){let a=e.enabledWhen!==void 0&&(i??0)<.5,o=r||a;return(0,G.jsxs)(q,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`},children:[(0,G.jsx)(Zu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`50%`,flexShrink:0},children:e.label}),(0,G.jsx)(q,{style:{width:`50%`},children:(0,G.jsx)(fg,{value:t,onChange:t=>n(e.id,t),min:e.min,max:e.max,step:e.step,size:`xs`,disabled:o,styles:{root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}}})})]})}function Wg({command:e,value:t,onChange:n,disabled:r}){return(0,G.jsx)(q,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(af,{label:e.label,checked:t>=.5,onChange:t=>n(e.id,+!!t.currentTarget.checked),size:`xs`,disabled:r})})}function Gg(e){let{visible:t,onVisibleChange:n,projects:r,projectValue:i,projectLabel:a,onProjectChange:o,scenes:s,sceneValue:c,onSceneChange:l,splats:u,splatSection:d=!1,splatValue:f,onSplatChange:p,splatConfig:m,onCalibrateSplat:h,onSplatUrlLoad:g,policies:_,policyValue:v,onPolicyChange:y,motions:x,motionValue:S,onMotionChange:C,showReferenceMotion:w,onShowReferenceMotionChange:T,commandsEnabled:E=!1,commands:D,commandValues:O,onCommandChange:k,onReset:A}=e,[j,{open:M,close:N}]=Ut(!1),[P,F]=(0,b.useState)(``),[I,L]=(0,b.useState)(null),[R,z]=(0,b.useState)(!1),B=(0,b.useCallback)(async e=>{if(e.key!==`Enter`||!g)return;let t=P.trim();if(!u.some(e=>e.label===t||e.value===t)){if(!t.toLowerCase().endsWith(`.spz`)){L(`URL must end with .spz`);return}await g(t)?(L(null),z(!0)):L(`File not found at the specified URL`)}},[g,P,u]),V=Array.from(new Set(D.map(e=>e.group))),ee=(0,b.useCallback)(()=>{A?.()},[A]);(0,b.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.repeat||e.altKey||e.ctrlKey||e.metaKey)return;let r=e.key.toLowerCase();r!==`c`&&r!==`r`||Vg(e.target instanceof Element?e.target:document.activeElement)||(e.preventDefault(),r===`c`?n(!t):ee())};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,n,ee]);let te=e=>D.filter(t=>t.group===e&&(t.type===`slider`||t.type===`checkbox`));return!r.length&&!s.length&&!_.length?null:(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Cm,{opened:j,onClose:N,size:`lg`,title:null,centered:!0,styles:{body:{textAlign:`center`}},children:(0,G.jsxs)(gg,{gap:`md`,align:`center`,children:[(0,G.jsx)(vp,{src:`/logo.svg`,style:{width:`8em`,height:`auto`}}),(0,G.jsx)(Zu,{size:`xl`,fw:700,children:`powered by mjswan`}),(0,G.jsxs)(Zu,{size:`sm`,c:`dimmed`,children:[`version `,Tg]}),(0,G.jsx)(Zu,{size:`sm`,c:`dimmed`,children:`MuJoco Simulation on Web Assembly with Neural netwroks`}),(0,G.jsx)(hp,{w:`100%`}),(0,G.jsxs)(q,{children:[(0,G.jsx)(ed,{href:`https://github.com/ttktjmt/mjswan`,target:`_blank`,style:{fontWeight:`600`},children:`GitHub`}),`\xA0\xA0•\xA0\xA0`,(0,G.jsx)(ed,{href:`https://mjswan.readthedocs.io`,target:`_blank`,style:{fontWeight:`600`},children:`Documentation`})]}),(0,G.jsx)(hp,{w:`100%`}),(0,G.jsxs)(q,{style:{textAlign:`left`,maxHeight:`120px`,overflowY:`auto`,lineHeight:`1`,fontSize:`0.8rem`,opacity:`0.75`},px:`md`,children:[`Thanks to our contributors! `,(0,G.jsx)(`br`,{}),Eg.map((e,t)=>(0,G.jsxs)(`span`,{children:[(0,G.jsx)(ed,{href:e.html_url,target:`_blank`,style:{textDecoration:`none`,fontSize:`0.75rem`},children:e.login}),t<Eg.length-1&&`, `]},e.login))]})]})}),(0,G.jsxs)(Mg,{width:`20em`,visible:t,onVisibleChange:n,hiddenButtonTooltip:`Show controls (C)`,children:[(0,G.jsxs)(Mg.Handle,{children:[(0,G.jsx)(Gh,{label:`mjswan ${Tg}`,children:(0,G.jsx)(q,{component:`a`,onClick:e=>{e.stopPropagation(),M()},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{position:`absolute`,cursor:`pointer`,display:`flex`,top:`0.8em`,left:`0.9em`},children:(0,G.jsx)(vp,{src:`/logo.svg`,style:{width:`1.2em`,height:`auto`}})})}),(0,G.jsx)(`div`,{style:{width:`1.1em`}}),(0,G.jsx)(Mg.HideWhenCollapsed,{children:(0,G.jsxs)(q,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`,display:`flex`,alignItems:`center`,gap:`0.5em`},pt:`0.1em`,children:[(0,G.jsx)(`span`,{style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:a}),r.length>1&&(0,G.jsxs)(om,{position:`bottom-start`,offset:5,children:[(0,G.jsx)(om.Target,{children:(0,G.jsx)(q,{onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{cursor:`pointer`,display:`flex`,alignItems:`center`,flexShrink:0},children:(0,G.jsx)(bg,{size:16})})}),(0,G.jsx)(om.Dropdown,{onClick:e=>e.stopPropagation(),children:r.map(e=>(0,G.jsx)(om.Item,{onClick:t=>{t.stopPropagation(),o(e.value)},style:{fontWeight:e.value===i?600:400,backgroundColor:e.value===i?`rgba(34, 139, 230, 0.1)`:void 0},children:e.label},e.value))})]})]})}),(0,G.jsx)(Mg.HideWhenExpanded,{children:(0,G.jsx)(q,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`},pt:`0.1em`,children:a})}),(0,G.jsx)(Gh,{label:`Hide controls (C)`,children:(0,G.jsx)(ql,{variant:`subtle`,color:`gray`,size:`sm`,"aria-label":`Hide controls`,onClick:e=>{e.stopPropagation(),n(!1)},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),children:(0,G.jsx)(Cg,{size:14})})})]}),(0,G.jsx)(Mg.Contents,{children:(0,G.jsxs)(q,{pt:`0.375em`,children:[s.length>0&&(0,G.jsx)(Ng,{id:`scene-select`,label:`Scene`,children:(0,G.jsx)(qh,{id:`scene-select`,placeholder:`Select scene`,data:s,value:c,onChange:l,size:`xs`,radius:`xs`,searchable:!0,clearable:!1,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(u.length>0||d)&&(0,G.jsx)(Ng,{id:`splat-select`,label:`Splat`,children:(0,G.jsx)(Gh,{label:I??``,color:`red`,position:`bottom`,opened:I!==null,withArrow:!0,children:(0,G.jsx)(qh,{id:`splat-select`,placeholder:g===void 0?`Select splat`:`Select splat or paste .spz URL`,data:u,value:f,onChange:e=>{p(e),L(null),z(!1)},searchable:g!==void 0,searchValue:P,onSearchChange:e=>{F(e),e&&L(null)},onKeyDown:B,size:`xs`,radius:`xs`,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})})}),(m?.control&&f!==null||R)&&h&&(0,G.jsx)(Bg,{scale:m?.scale??1,xOffset:m?.xOffset??0,yOffset:m?.yOffset??0,zOffset:m?.zOffset??0,roll:m?.roll??0,pitch:m?.pitch??0,yaw:m?.yaw??0,onCalibrate:h}),_.length>0&&(0,G.jsx)(Ng,{id:`policy-select`,label:`Policy`,children:(0,G.jsx)(qh,{id:`policy-select`,placeholder:`Select policy`,data:_,value:v,onChange:y,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),x.length>0&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Ng,{id:`motion-select`,label:`Motion`,children:(0,G.jsx)(qh,{id:`motion-select`,placeholder:`Select motion`,data:x,value:S,onChange:C,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(0,G.jsx)(q,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(af,{label:`Show reference`,checked:w,onChange:e=>T(e.currentTarget.checked),size:`xs`})})]}),V.length>0&&D.some(e=>e.type===`slider`||e.type===`checkbox`)&&(0,G.jsx)(G.Fragment,{children:V.map(e=>{let t=te(e);return t.length===0?null:(0,G.jsx)(Pg,{label:Hg(e),expandByDefault:!0,children:t.map(e=>e.type===`checkbox`?(0,G.jsx)(Wg,{command:e,value:O[e.id]??0,onChange:k,disabled:!E},e.id):e.type===`slider`?(0,G.jsx)(Ug,{command:e,value:O[e.id]??0,onChange:k,disabled:!E,enabledWhenValue:e.enabledWhen?O[`${e.group}:${e.enabledWhen}`]:void 0},e.id):null)},e)})}),(0,G.jsx)(hp,{mb:`xs`,mx:`xs`}),(0,G.jsx)(q,{px:`xs`,pb:`xs`,children:(0,G.jsx)(xf,{variant:`light`,color:`red`,size:`xs`,fullWidth:!0,leftSection:(0,G.jsx)(Sg,{size:14}),onClick:ee,children:`Reset`})})]})})]})]})}function Kg(e,t,n){return Object.keys(e[t]).reduce((e,t)=>(e[t]=`var(--mantine-${n}-${t})`,e),{})}function qg(e,t){return e in t.breakpoints?t.breakpoints[e]:Be(e)}function Jg(e){let t=Wn(Ln,e),n=Kg(t,`fontSizes`,`font-size`),r=Kg(t,`lineHeights`,`line-height`),i=Kg(t,`shadows`,`shadow`),a=Kg(t,`radius`,`radius`),o=Kg(t,`spacing`,`spacing`),s=Object.keys(t.headings.sizes).reduce((e,t)=>(e[t]={fontSize:`var(--mantine-${t}-font-size)`,lineHeight:`var(--mantine-${t}-line-height)`,fontWeight:`var(--mantine-${t}-font-weight)`},e),{}),c=Object.keys(t.colors).reduce((e,t)=>(e[t]={0:`var(--mantine-color-${t}-0)`,1:`var(--mantine-color-${t}-1)`,2:`var(--mantine-color-${t}-2)`,3:`var(--mantine-color-${t}-3)`,4:`var(--mantine-color-${t}-4)`,5:`var(--mantine-color-${t}-5)`,6:`var(--mantine-color-${t}-6)`,7:`var(--mantine-color-${t}-7)`,8:`var(--mantine-color-${t}-8)`,9:`var(--mantine-color-${t}-9)`,filled:`var(--mantine-color-${t}-filled)`,filledHover:`var(--mantine-color-${t}-filled-hover)`,light:`var(--mantine-color-${t}-light)`,lightHover:`var(--mantine-color-${t}-light-hover)`,lightColor:`var(--mantine-color-${t}-light-color)`,outline:`var(--mantine-color-${t}-outline)`,outlineHover:`var(--mantine-color-${t}-outline-hover)`},e),{primary:`var(--mantine-primary-color-filled)`,primaryColors:{0:`var(--mantine-primary-color-0)`,1:`var(--mantine-primary-color-1)`,2:`var(--mantine-primary-color-2)`,3:`var(--mantine-primary-color-3)`,4:`var(--mantine-primary-color-4)`,5:`var(--mantine-primary-color-5)`,6:`var(--mantine-primary-color-6)`,7:`var(--mantine-primary-color-7)`,8:`var(--mantine-primary-color-8)`,9:`var(--mantine-primary-color-9)`,filled:`var(--mantine-primary-color-filled)`,filledHover:`var(--mantine-primary-color-filled-hover)`,light:`var(--mantine-primary-color-light)`,lightHover:`var(--mantine-primary-color-light-hover)`,lightColor:`var(--mantine-primary-color-light-color)`,outline:`var(--mantine-primary-color-outline)`,outlineHover:`var(--mantine-primary-color-outline-hover)`},white:`var(--mantine-color-white)`,black:`var(--mantine-color-black)`,text:`var(--mantine-color-text)`,body:`var(--mantine-color-body)`,error:`var(--mantine-color-error)`,placeholder:`var(--mantine-color-placeholder)`,anchor:`var(--mantine-color-anchor)`,default:`var(--mantine-color-default)`,defaultHover:`var(--mantine-color-default-hover)`,defaultColor:`var(--mantine-color-default-color)`,defaultBorder:`var(--mantine-color-default-border)`,dimmed:`var(--mantine-color-dimmed)`,disabledBody:`var(--mantine-color-disabled)`,disabledText:`var(--mantine-color-disabled-color)`,disabledBorder:`var(--mantine-color-disabled-border)`});return{scale:`var(--mantine-scale)`,cursorType:`var(--mantine-cursor-type)`,webkitFontSmoothing:`var(--mantine-webkit-font-smoothing)`,mozFontSmoothing:`var(--mantine-moz-font-smoothing)`,lineHeight:`var(--mantine-line-height)`,fontFamily:`var(--mantine-font-family)`,fontFamilyMonospace:`var(--mantine-font-family-monospace)`,fontFamilyHeadings:`var(--mantine-font-family-headings)`,headingFontWeight:`var(--mantine-heading-font-weight)`,radiusDefault:`var(--mantine-radius-default)`,breakpoints:t.breakpoints,fontSizes:n,lineHeights:r,shadows:i,radius:a,headings:s,spacing:o,colors:c,rtlSelector:`[dir="rtl"] &`,darkSelector:`[data-mantine-color-scheme="dark"] &`,lightSelector:`[data-mantine-color-scheme="light"] &`,smallerThan:e=>`(max-width: ${qg(e,t)})`,largerThan:e=>`(min-width: ${qg(e,t)})`}}var Yg=Nr({fontFamily:`Inter`,autoContrast:!0,components:{Checkbox:af.extend({defaultProps:{radius:`xs`}}),ColorInput:dp.extend({defaultProps:{radius:`xs`}}),Select:qh.extend({defaultProps:{radius:`sm`}}),Textarea:Hp.extend({defaultProps:{radius:`xs`}}),TextInput:_g.extend({defaultProps:{radius:`xs`}}),NumberInput:Dh.extend({defaultProps:{radius:`xs`}}),Paper:Xc.extend({defaultProps:{radius:`xs`,shadow:`0`}}),ActionIcon:ql.extend({defaultProps:{variant:`subtle`,color:`gray`,radius:`xs`}}),Button:xf.extend({defaultProps:{radius:`xs`,styles:{label:{fontWeight:450}}}})}});Jg(Yg);var Xg=(0,b.createContext)(void 0),Zg=()=>{let e=(0,b.useContext)(Xg);if(!e)throw Error(`useLoading must be used within a LoadingProvider`);return e},Qg=({children:e})=>{let[t,n]=(0,b.useState)(!1),[r,i]=(0,b.useState)(null),a=(0,b.useCallback)(e=>{e!==void 0&&i(e),n(!0)},[]),o=(0,b.useCallback)(e=>{i(e)},[]),s=(0,b.useCallback)(()=>{n(!1),i(null)},[]);return(0,G.jsx)(Xg.Provider,{value:{isLoading:t,loadingMessage:r,showLoading:a,setLoadingMessage:o,hideLoading:s},children:e})},$g=()=>{let{isLoading:e,loadingMessage:t}=Zg();return e?(0,G.jsx)(`div`,{className:`loader-overlay`,children:(0,G.jsxs)(`div`,{className:`loader-content`,children:[(0,G.jsx)(zl,{size:64,type:`bars`}),t&&(0,G.jsx)(`p`,{className:`loader-message`,children:t})]})}):null},e_=!1;function t_(){typeof window>`u`||(window.__mjswanReady=!0,e_||(e_=!0,window.dispatchEvent(new CustomEvent(`mjswan:ready`))))}function n_(){typeof window>`u`||(window.__mjswanError=!0)}var r_={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},i_={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},a_=`attached`,o_=`detached`,s_=1e3,c_=1001,l_=1002,u_=1003,d_=1004,f_=1004,p_=1005,m_=1005,h_=1006,g_=1007,__=1007,v_=1008,y_=1008,b_=1009,x_=1010,S_=1011,C_=1012,w_=1013,T_=1014,E_=1015,D_=1016,O_=1017,k_=1018,A_=1020,j_=35902,M_=35899,N_=1021,P_=1022,F_=1023,I_=1026,L_=1027,R_=1028,z_=1029,B_=1030,V_=1031,H_=1032,U_=1033,W_=33776,G_=33777,K_=33778,q_=33779,J_=35840,Y_=35841,X_=35842,Z_=35843,Q_=36196,$_=37492,ev=37496,tv=37808,nv=37809,rv=37810,iv=37811,av=37812,ov=37813,sv=37814,cv=37815,lv=37816,uv=37817,dv=37818,fv=37819,pv=37820,mv=37821,hv=36492,gv=36494,_v=36495,vv=36283,yv=36284,bv=36285,xv=36286,Sv=2200,Cv=2201,wv=2202,Tv=2300,Ev=2301,Dv=2302,Ov=2400,kv=2401,Av=2402,jv=2500,Mv=2501,Nv=3200,Pv=3201,Fv=3202,Iv=3203,Lv=`srgb`,Rv=`srgb-linear`,zv=`linear`,Bv=`srgb`,Vv=7680,Hv=7681,Uv=7682,Wv=7683,Gv=34055,Kv=34056,qv=5386,Jv=35044,Yv=35048,Xv=35040,Zv=35045,Qv=35049,$v=35041,ey=35046,ty=35050,ny=35042,ry=`300 es`,iy=2e3,ay=2001,oy={COMPUTE:`compute`,RENDER:`render`},sy={PERSPECTIVE:`perspective`,LINEAR:`linear`,FLAT:`flat`},cy={NORMAL:`normal`,CENTROID:`centroid`,SAMPLE:`sample`,FIRST:`first`,EITHER:`either`};function ly(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}var uy={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function dy(e,t){return new uy[e](t)}function fy(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function py(){let e=fy(`canvas`);return e.style.display=`block`,e}var my={},hy=null;function gy(e){hy=e}function _y(){return hy}function vy(...e){let t=`THREE.`+e.shift();hy?hy(`log`,t,...e):console.log(t,...e)}function yy(...e){let t=`THREE.`+e.shift();hy?hy(`warn`,t,...e):console.warn(t,...e)}function by(...e){let t=`THREE.`+e.shift();hy?hy(`error`,t,...e):console.error(t,...e)}function xy(...e){let t=e.join(` `);t in my||(my[t]=!0,yy(...e))}function Sy(e,t,n){return new Promise(function(r,i){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()}}setTimeout(a,n)})}var Cy=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?!1: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<r;n++)t[n].call(this,e);e.target=null}}},wy=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),Ty=1234567,Ey=Math.PI/180,Dy=180/Math.PI;function Oy(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(wy[e&255]+wy[e>>8&255]+wy[e>>16&255]+wy[e>>24&255]+`-`+wy[t&255]+wy[t>>8&255]+`-`+wy[t>>16&15|64]+wy[t>>24&255]+`-`+wy[n&63|128]+wy[n>>8&255]+`-`+wy[n>>16&255]+wy[n>>24&255]+wy[r&255]+wy[r>>8&255]+wy[r>>16&255]+wy[r>>24&255]).toLowerCase()}function ky(e,t,n){return Math.max(t,Math.min(n,e))}function Ay(e,t){return(e%t+t)%t}function jy(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function My(e,t,n){return e===t?0:(n-e)/(t-e)}function Ny(e,t,n){return(1-n)*e+n*t}function Py(e,t,n,r){return Ny(e,t,1-Math.exp(-n*r))}function Fy(e,t=1){return t-Math.abs(Ay(e,t*2)-t)}function Iy(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function Ly(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function Ry(e,t){return e+Math.floor(Math.random()*(t-e+1))}function zy(e,t){return e+Math.random()*(t-e)}function By(e){return e*(.5-Math.random())}function Vy(e){e!==void 0&&(Ty=e);let t=Ty+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Hy(e){return e*Ey}function Uy(e){return e*Dy}function Wy(e){return(e&e-1)==0&&e!==0}function Gy(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function Ky(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function qy(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:yy(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function Jy(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 Yy(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var Xy={DEG2RAD:Ey,RAD2DEG:Dy,generateUUID:Oy,clamp:ky,euclideanModulo:Ay,mapLinear:jy,inverseLerp:My,lerp:Ny,damp:Py,pingpong:Fy,smoothstep:Iy,smootherstep:Ly,randInt:Ry,randFloat:zy,randFloatSpread:By,seededRandom:Vy,degToRad:Hy,radToDeg:Uy,isPowerOfTwo:Wy,ceilPowerOfTwo:Gy,floorPowerOfTwo:Ky,setQuaternionFromProperEuler:qy,normalize:Yy,denormalize:Jy},J=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=ky(this.x,e.x,t.x),this.y=ky(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ky(this.x,e,t),this.y=ky(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ky(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(ky(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}},Zy=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){e[t+0]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u;return}if(o>=1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;return}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,o=Math.sin(o*n)/r,s=s*t+d*o,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:yy(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&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(ky(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}},Y=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($y.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion($y.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=ky(this.x,e.x,t.x),this.y=ky(this.y,e.y,t.y),this.z=ky(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ky(this.x,e,t),this.y=ky(this.y,e,t),this.z=ky(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ky(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 Qy.copy(this).projectOnVector(e),this.sub(Qy)}reflect(e){return this.sub(Qy.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(ky(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,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-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}},Qy=new Y,$y=new Zy,eb=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(tb.makeScale(e,t)),this}rotate(e){return this.premultiply(tb.makeRotation(-e)),this}translate(e,t){return this.premultiply(tb.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)}},tb=new eb,nb=new eb().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),rb=new eb().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ib(){let e={enabled:!0,workingColorSpace:Rv,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=ob(e.r),e.g=ob(e.g),e.b=ob(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===`srgb`&&(e.r=sb(e.r),e.g=sb(e.g),e.b=sb(e.b)),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===``?zv: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 xy(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return xy(`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({[Rv]:{primaries:t,whitePoint:r,transfer:zv,toXYZ:nb,fromXYZ:rb,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Lv},outputColorSpaceConfig:{drawingBufferColorSpace:Lv}},[Lv]:{primaries:t,whitePoint:r,transfer:Bv,toXYZ:nb,fromXYZ:rb,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Lv}}}),e}var ab=ib();function ob(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function sb(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var cb,lb=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{cb===void 0&&(cb=fy(`canvas`)),cb.width=e.width,cb.height=e.height;let t=cb.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=cb}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=fy(`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;e<i.length;e++)i[e]=ob(i[e]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(ob(t[e]/255)*255):t[e]=ob(t[e]);return{data:t,width:e.width,height:e.height}}else return yy(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},ub=0,db=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ub++}),this.uuid=Oy(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(fb(r[t].image)):e.push(fb(r[t]))}else e=fb(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function fb(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?lb.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(yy(`Texture: Unable to serialize Texture.`),{})}var pb=0,mb=new Y,hb=class e extends Cy{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=c_,i=c_,a=h_,o=v_,s=F_,c=b_,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:pb++}),this.uuid=Oy(),this.name=``,this.source=new db(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new J(0,0),this.repeat=new J(1,1),this.center=new J(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new eb,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(mb).x}get height(){return this.source.getSize(mb).y}get depth(){return this.source.getSize(mb).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){yy(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){yy(`Texture.setValues(): property '${t}' does not exist.`);continue}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 s_:e.x-=Math.floor(e.x);break;case c_:e.x=e.x<0?0:1;break;case l_:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case s_:e.y-=Math.floor(e.y);break;case c_:e.y=e.y<0?0:1;break;case l_:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};hb.DEFAULT_IMAGE=null,hb.DEFAULT_MAPPING=300,hb.DEFAULT_ANISOTROPY=1;var gb=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)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ky(this.x,e.x,t.x),this.y=ky(this.y,e.y,t.y),this.z=ky(this.z,e.z,t.z),this.w=ky(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ky(this.x,e,t),this.y=ky(this.y,e,t),this.z=ky(this.z,e,t),this.w=ky(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ky(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,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.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},_b=class extends Cy{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:h_,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new gb(0,0,e,t),this.scissorTest=!1,this.viewport=new gb(0,0,e,t);let r=new hb({width:e,height:t,depth:n.depth});this.textures=[];let i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:h_,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);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<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new db(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:`dispose`})}},vb=class extends _b{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},yb=class extends hb{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=u_,this.minFilter=u_,this.wrapR=c_,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},bb=class extends vb{constructor(e=1,t=1,n=1,r={}){super(e,t,r),this.isWebGLArrayRenderTarget=!0,this.depth=n,this.texture=new yb(null,e,t,n),this._setTextureOptions(r),this.texture.isRenderTargetTexture=!0}},xb=class extends hb{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=u_,this.minFilter=u_,this.wrapR=c_,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Sb=class extends vb{constructor(e=1,t=1,n=1,r={}){super(e,t,r),this.isWebGL3DRenderTarget=!0,this.depth=n,this.texture=new xb(null,e,t,n),this._setTextureOptions(r),this.texture.isRenderTargetTexture=!0}},Cb=class{constructor(e=new Y(1/0,1/0,1/0),t=new Y(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Tb.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Tb.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Tb.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,Tb):Tb.fromBufferAttribute(r,t),Tb.applyMatrix4(e.matrixWorld),this.expandByPoint(Tb);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Eb.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Eb.copy(e.boundingBox)),Eb.applyMatrix4(e.matrixWorld),this.union(Eb)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=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,Tb),Tb.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(Nb),Pb.subVectors(this.max,Nb),Db.subVectors(e.a,Nb),Ob.subVectors(e.b,Nb),kb.subVectors(e.c,Nb),Ab.subVectors(Ob,Db),jb.subVectors(kb,Ob),Mb.subVectors(Db,kb);let t=[0,-Ab.z,Ab.y,0,-jb.z,jb.y,0,-Mb.z,Mb.y,Ab.z,0,-Ab.x,jb.z,0,-jb.x,Mb.z,0,-Mb.x,-Ab.y,Ab.x,0,-jb.y,jb.x,0,-Mb.y,Mb.x,0];return!Lb(t,Db,Ob,kb,Pb)||(t=[1,0,0,0,1,0,0,0,1],!Lb(t,Db,Ob,kb,Pb))?!1:(Fb.crossVectors(Ab,jb),t=[Fb.x,Fb.y,Fb.z],Lb(t,Db,Ob,kb,Pb))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Tb).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Tb).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(wb[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wb[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wb[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wb[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wb[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wb[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wb[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wb[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wb),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}},wb=[new Y,new Y,new Y,new Y,new Y,new Y,new Y,new Y],Tb=new Y,Eb=new Cb,Db=new Y,Ob=new Y,kb=new Y,Ab=new Y,jb=new Y,Mb=new Y,Nb=new Y,Pb=new Y,Fb=new Y,Ib=new Y;function Lb(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Ib.fromArray(e,a);let o=i.x*Math.abs(Ib.x)+i.y*Math.abs(Ib.y)+i.z*Math.abs(Ib.z),s=t.dot(Ib),c=n.dot(Ib),l=r.dot(Ib);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var Rb=new Cb,zb=new Y,Bb=new Y,Vb=class{constructor(e=new Y,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?Rb.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.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;zb.subVectors(e,this.center);let t=zb.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(zb,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Bb.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(zb.copy(e.center).add(Bb)),this.expandByPoint(zb.copy(e.center).sub(Bb))),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}},Hb=new Y,Ub=new Y,Wb=new Y,Gb=new Y,Kb=new Y,qb=new Y,Jb=new Y,Yb=class{constructor(e=new Y,t=new Y(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,Hb)),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=Hb.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Hb.copy(this.origin).addScaledVector(this.direction,t),Hb.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){Ub.copy(e).add(t).multiplyScalar(.5),Wb.copy(t).sub(e).normalize(),Gb.copy(this.origin).sub(Ub);let i=e.distanceTo(t)*.5,a=-this.direction.dot(Wb),o=Gb.dot(this.direction),s=-Gb.dot(Wb),c=Gb.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(Ub).addScaledVector(Wb,d),f}intersectSphere(e,t){Hb.subVectors(e.center,this.origin);let n=Hb.dot(this.direction),r=Hb.dot(Hb)-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?!1: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||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||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=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)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Hb)!==null}intersectTriangle(e,t,n,r,i){Kb.subVectors(t,e),qb.subVectors(n,e),Jb.crossVectors(Kb,qb);let a=this.direction.dot(Jb),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Gb.subVectors(this.origin,e);let s=o*this.direction.dot(qb.crossVectors(Gb,qb));if(s<0)return null;let c=o*this.direction.dot(Kb.cross(Gb));if(c<0||s+c>a)return null;let l=-o*Gb.dot(Jb);return l<0?null:this.at(l/a,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)}},Xb=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/Zb.setFromMatrixColumn(e,0).length(),i=1/Zb.setFromMatrixColumn(e,1).length(),a=1/Zb.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($b,e,ex)}lookAt(e,t,n){let r=this.elements;return rx.subVectors(e,t),rx.lengthSq()===0&&(rx.z=1),rx.normalize(),tx.crossVectors(n,rx),tx.lengthSq()===0&&(Math.abs(n.z)===1?rx.x+=1e-4:rx.z+=1e-4,rx.normalize(),tx.crossVectors(n,rx)),tx.normalize(),nx.crossVectors(rx,tx),r[0]=tx.x,r[4]=nx.x,r[8]=rx.x,r[1]=tx.y,r[5]=nx.y,r[9]=rx.y,r[2]=tx.z,r[6]=nx.z,r[10]=rx.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],P=r[7],F=r[11],I=r[15];return i[0]=a*x+o*T+s*k+c*N,i[4]=a*S+o*E+s*A+c*P,i[8]=a*C+o*D+s*j+c*F,i[12]=a*w+o*O+s*M+c*I,i[1]=l*x+u*T+d*k+f*N,i[5]=l*S+u*E+d*A+f*P,i[9]=l*C+u*D+d*j+f*F,i[13]=l*w+u*O+d*M+f*I,i[2]=p*x+m*T+h*k+g*N,i[6]=p*S+m*E+h*A+g*P,i[10]=p*C+m*D+h*j+g*F,i[14]=p*w+m*O+h*M+g*I,i[3]=_*x+v*T+y*k+b*N,i[7]=_*S+v*E+y*A+b*P,i[11]=_*C+v*D+y*j+b*F,i[15]=_*w+v*O+y*M+b*I,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],p=e[3],m=e[7],h=e[11],g=e[15];return p*(+i*s*u-r*c*u-i*o*d+n*c*d+r*o*f-n*s*f)+m*(+t*s*f-t*c*d+i*a*d-r*a*f+r*c*l-i*s*l)+h*(+t*c*u-t*o*f-i*a*u+n*a*f+i*o*l-n*c*l)+g*(-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=Zb.set(r[0],r[1],r[2]).length(),a=Zb.set(r[4],r[5],r[6]).length(),o=Zb.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],Qb.copy(this);let s=1/i,c=1/a,l=1/o;return Qb.elements[0]*=s,Qb.elements[1]*=s,Qb.elements[2]*=s,Qb.elements[4]*=c,Qb.elements[5]*=c,Qb.elements[6]*=c,Qb.elements[8]*=l,Qb.elements[9]*=l,Qb.elements[10]*=l,t.setFromRotationMatrix(Qb),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a,o=iy,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===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);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=iy,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===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);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}},Zb=new Y,Qb=new Xb,$b=new Y(0,0,0),ex=new Y(1,1,1),tx=new Y,nx=new Y,rx=new Y,ix=new Xb,ax=new Zy,ox=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(ky(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(-ky(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(ky(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(-ky(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(ky(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(-ky(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:yy(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return ix.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ix,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ax.setFromEuler(this),this.setFromQuaternion(ax,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}};ox.DEFAULT_ORDER=`XYZ`;var sx=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!=0}},cx=0,lx=new Y,ux=new Zy,dx=new Xb,fx=new Y,px=new Y,mx=new Y,hx=new Zy,gx=new Y(1,0,0),_x=new Y(0,1,0),vx=new Y(0,0,1),yx={type:`added`},bx={type:`removed`},xx={type:`childadded`,child:null},Sx={type:`childremoved`,child:null},Cx=class e extends Cy{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:cx++}),this.uuid=Oy(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new Y,n=new ox,r=new Zy,i=new Y(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Xb},normalMatrix:{value:new eb}}),this.matrix=new Xb,this.matrixWorld=new Xb,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new sx,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return ux.setFromAxisAngle(e,t),this.quaternion.multiply(ux),this}rotateOnWorldAxis(e,t){return ux.setFromAxisAngle(e,t),this.quaternion.premultiply(ux),this}rotateX(e){return this.rotateOnAxis(gx,e)}rotateY(e){return this.rotateOnAxis(_x,e)}rotateZ(e){return this.rotateOnAxis(vx,e)}translateOnAxis(e,t){return lx.copy(e).applyQuaternion(this.quaternion),this.position.add(lx.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(gx,e)}translateY(e){return this.translateOnAxis(_x,e)}translateZ(e){return this.translateOnAxis(vx,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(dx.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?fx.copy(e):fx.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),px.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?dx.lookAt(px,fx,this.up):dx.lookAt(fx,px,this.up),this.quaternion.setFromRotationMatrix(dx),r&&(dx.extractRotation(r.matrixWorld),ux.setFromRotationMatrix(dx),this.quaternion.premultiply(ux.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(by(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(yx),xx.child=e,this.dispatchEvent(xx),xx.child=null):by(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(bx),Sx.child=e,this.dispatchEvent(Sx),Sx.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),dx.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),dx.multiply(e.parent.matrixWorld)),e.applyMatrix4(dx),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(yx),xx.child=e,this.dispatchEvent(xx),xx.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(px,e,mx),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(px,hx,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let e=this.children;for(let t=0,n=e.length;t<n;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==``&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(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()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(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&&this.environment.isRenderTargetTexture!==!0&&(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;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(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)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}};Cx.DEFAULT_UP=new Y(0,1,0),Cx.DEFAULT_MATRIX_AUTO_UPDATE=!0,Cx.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var wx=new Y,Tx=new Y,Ex=new Y,Dx=new Y,Ox=new Y,kx=new Y,Ax=new Y,jx=new Y,Mx=new Y,Nx=new Y,Px=new gb,Fx=new gb,Ix=new gb,Lx=class e{constructor(e=new Y,t=new Y,n=new Y){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),wx.subVectors(e,t),r.cross(wx);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){wx.subVectors(r,t),Tx.subVectors(n,t),Ex.subVectors(e,t);let a=wx.dot(wx),o=wx.dot(Tx),s=wx.dot(Ex),c=Tx.dot(Tx),l=Tx.dot(Ex),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,Dx)===null?!1:Dx.x>=0&&Dx.y>=0&&Dx.x+Dx.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Dx)===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,Dx.x),s.addScaledVector(a,Dx.y),s.addScaledVector(o,Dx.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Px.setScalar(0),Fx.setScalar(0),Ix.setScalar(0),Px.fromBufferAttribute(e,t),Fx.fromBufferAttribute(e,n),Ix.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Px,i.x),a.addScaledVector(Fx,i.y),a.addScaledVector(Ix,i.z),a}static isFrontFacing(e,t,n,r){return wx.subVectors(n,t),Tx.subVectors(e,t),wx.cross(Tx).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 wx.subVectors(this.c,this.b),Tx.subVectors(this.a,this.b),wx.cross(Tx).length()*.5}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;Ox.subVectors(r,n),kx.subVectors(i,n),jx.subVectors(e,n);let s=Ox.dot(jx),c=kx.dot(jx);if(s<=0&&c<=0)return t.copy(n);Mx.subVectors(e,r);let l=Ox.dot(Mx),u=kx.dot(Mx);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(Ox,a);Nx.subVectors(e,i);let f=Ox.dot(Nx),p=kx.dot(Nx);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(kx,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Ax.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Ax,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Ox,a).addScaledVector(kx,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Rx={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},zx={h:0,s:0,l:0},Bx={h:0,s:0,l:0};function Vx(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var X=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=Lv){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,ab.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=ab.workingColorSpace){return this.r=e,this.g=t,this.b=n,ab.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=ab.workingColorSpace){if(e=Ay(e,1),t=ky(t,0,1),n=ky(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=Vx(i,r,e+1/3),this.g=Vx(i,r,e),this.b=Vx(i,r,e-1/3)}return ab.colorSpaceToWorking(this,r),this}setStyle(e,t=Lv){function n(t){t!==void 0&&parseFloat(t)<1&&yy(`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:yy(`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);yy(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Lv){let n=Rx[e.toLowerCase()];return n===void 0?yy(`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=ob(e.r),this.g=ob(e.g),this.b=ob(e.b),this}copyLinearToSRGB(e){return this.r=sb(e.r),this.g=sb(e.g),this.b=sb(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Lv){return ab.workingToColorSpace(Hx.copy(this),e),Math.round(ky(Hx.r*255,0,255))*65536+Math.round(ky(Hx.g*255,0,255))*256+Math.round(ky(Hx.b*255,0,255))}getHexString(e=Lv){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ab.workingColorSpace){ab.workingToColorSpace(Hx.copy(this),t);let n=Hx.r,r=Hx.g,i=Hx.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+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4;break}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=ab.workingColorSpace){return ab.workingToColorSpace(Hx.copy(this),t),e.r=Hx.r,e.g=Hx.g,e.b=Hx.b,e}getStyle(e=Lv){ab.workingToColorSpace(Hx.copy(this),e);let t=Hx.r,n=Hx.g,r=Hx.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(zx),this.setHSL(zx.h+e,zx.s+t,zx.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(zx),e.getHSL(Bx);let n=Ny(zx.h,Bx.h,t),r=Ny(zx.s,Bx.s,t),i=Ny(zx.l,Bx.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Hx=new X;X.NAMES=Rx;var Ux=0,Wx=class extends Cy{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Ux++}),this.uuid=Oy(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new X(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Vv,this.stencilZFail=Vv,this.stencilZPass=Vv,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=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){yy(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){yy(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}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`}};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),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(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),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(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!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(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),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(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){e===!0&&this.version++}},Gx=class extends Wx{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new X(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 ox,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}},Kx=qx();function qx(){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[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=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(;!(t&8388608);)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}}function Jx(e){Math.abs(e)>65504&&yy(`DataUtils.toHalfFloat(): Value out of range.`),e=ky(e,-65504,65504),Kx.floatView[0]=e;let t=Kx.uint32View[0],n=t>>23&511;return Kx.baseTable[n]+((t&8388607)>>Kx.shiftTable[n])}function Yx(e){let t=e>>10;return Kx.uint32View[0]=Kx.mantissaTable[Kx.offsetTable[t]+(e&1023)]+Kx.exponentTable[t],Kx.floatView[0]}var Xx=class{static toHalfFloat(e){return Jx(e)}static fromHalfFloat(e){return Yx(e)}},Zx=new Y,Qx=new J,$x=0,eS=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:$x++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Jv,this.updateRanges=[],this.gpuType=E_,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&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;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Qx.fromBufferAttribute(this,t),Qx.applyMatrix3(e),this.setXY(t,Qx.x,Qx.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.applyMatrix3(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.applyMatrix4(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.applyNormalMatrix(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Zx.fromBufferAttribute(this,t),Zx.transformDirection(e),this.setXYZ(t,Zx.x,Zx.y,Zx.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Jy(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Yy(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Jy(t,this.array)),t}setX(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Jy(t,this.array)),t}setY(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Jy(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Jy(t,this.array)),t}setW(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array),i=Yy(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==``&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}},tS=class extends eS{constructor(e,t,n){super(new Int8Array(e),t,n)}},nS=class extends eS{constructor(e,t,n){super(new Uint8Array(e),t,n)}},rS=class extends eS{constructor(e,t,n){super(new Uint8ClampedArray(e),t,n)}},iS=class extends eS{constructor(e,t,n){super(new Int16Array(e),t,n)}},aS=class extends eS{constructor(e,t,n){super(new Uint16Array(e),t,n)}},oS=class extends eS{constructor(e,t,n){super(new Int32Array(e),t,n)}},sS=class extends eS{constructor(e,t,n){super(new Uint32Array(e),t,n)}},cS=class extends eS{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=Yx(this.array[e*this.itemSize]);return this.normalized&&(t=Jy(t,this.array)),t}setX(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize]=Jx(t),this}getY(e){let t=Yx(this.array[e*this.itemSize+1]);return this.normalized&&(t=Jy(t,this.array)),t}setY(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+1]=Jx(t),this}getZ(e){let t=Yx(this.array[e*this.itemSize+2]);return this.normalized&&(t=Jy(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+2]=Jx(t),this}getW(e){let t=Yx(this.array[e*this.itemSize+3]);return this.normalized&&(t=Jy(t,this.array)),t}setW(e,t){return this.normalized&&(t=Yy(t,this.array)),this.array[e*this.itemSize+3]=Jx(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array)),this.array[e+0]=Jx(t),this.array[e+1]=Jx(n),this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array)),this.array[e+0]=Jx(t),this.array[e+1]=Jx(n),this.array[e+2]=Jx(r),this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=Yy(t,this.array),n=Yy(n,this.array),r=Yy(r,this.array),i=Yy(i,this.array)),this.array[e+0]=Jx(t),this.array[e+1]=Jx(n),this.array[e+2]=Jx(r),this.array[e+3]=Jx(i),this}},lS=class extends eS{constructor(e,t,n){super(new Float32Array(e),t,n)}},uS=0,dS=new Xb,fS=new Cx,pS=new Y,mS=new Cb,hS=new Cb,gS=new Y,_S=class e extends Cy{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:uS++}),this.uuid=Oy(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(ly(e)?sS:aS)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new eb().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return dS.makeRotationFromQuaternion(e),this.applyMatrix4(dS),this}rotateX(e){return dS.makeRotationX(e),this.applyMatrix4(dS),this}rotateY(e){return dS.makeRotationY(e),this.applyMatrix4(dS),this}rotateZ(e){return dS.makeRotationZ(e),this.applyMatrix4(dS),this}translate(e,t,n){return dS.makeTranslation(e,t,n),this.applyMatrix4(dS),this}scale(e,t,n){return dS.makeScale(e,t,n),this.applyMatrix4(dS),this}lookAt(e){return fS.lookAt(e),fS.updateMatrix(),this.applyMatrix4(fS.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(pS).negate(),this.translate(pS.x,pS.y,pS.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new lS(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&yy(`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 Cb);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){by(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new Y(-1/0,-1/0,-1/0),new Y(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];mS.setFromBufferAttribute(n),this.morphTargetsRelative?(gS.addVectors(this.boundingBox.min,mS.min),this.boundingBox.expandByPoint(gS),gS.addVectors(this.boundingBox.max,mS.max),this.boundingBox.expandByPoint(gS)):(this.boundingBox.expandByPoint(mS.min),this.boundingBox.expandByPoint(mS.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&by(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Vb);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){by(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new Y,1/0);return}if(e){let n=this.boundingSphere.center;if(mS.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];hS.setFromBufferAttribute(n),this.morphTargetsRelative?(gS.addVectors(mS.min,hS.min),mS.expandByPoint(gS),gS.addVectors(mS.max,hS.max),mS.expandByPoint(gS)):(mS.expandByPoint(hS.min),mS.expandByPoint(hS.max))}mS.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)gS.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(gS));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)gS.fromBufferAttribute(a,t),o&&(pS.fromBufferAttribute(e,t),gS.add(pS)),r=Math.max(r,n.distanceToSquared(gS))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&by(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){by(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv;this.hasAttribute(`tangent`)===!1&&this.setAttribute(`tangent`,new eS(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new Y,s[e]=new Y;let c=new Y,l=new Y,u=new Y,d=new J,f=new J,p=new J,m=new Y,h=new Y;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new Y,y=new Y,b=new Y,x=new Y;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0)n=new eS(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new Y,i=new Y,a=new Y,o=new Y,s=new Y,c=new Y,l=new Y,u=new Y;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)gS.fromBufferAttribute(e,t),gS.normalize(),e.setXYZ(t,gS.x,gS.y,gS.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new eS(a,r,i)}if(this.index===null)return yy(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.type,this.name!==``&&(e.name=this.name),Object.keys(this.userData).length>0&&(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;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(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;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:`dispose`})}},vS=new Xb,yS=new Yb,bS=new Vb,xS=new Y,SS=new Y,CS=new Y,wS=new Y,TS=new Y,ES=new Y,DS=new Y,OS=new Y,kS=class extends Cx{constructor(e=new _S,t=new Gx){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){ES.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(TS.fromBufferAttribute(s,e),a?ES.addScaledVector(TS,r):ES.addScaledVector(TS.sub(t),r))}t.add(ES)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),bS.copy(n.boundingSphere),bS.applyMatrix4(i),yS.copy(e.ray).recast(e.near),!(bS.containsPoint(yS.origin)===!1&&(yS.intersectSphere(bS,xS)===null||yS.origin.distanceToSquared(xS)>(e.far-e.near)**2))&&(vS.copy(i).invert(),yS.copy(e.ray).applyMatrix4(vS),!(n.boundingBox!==null&&yS.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,yS)))}_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;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=jS(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=jS(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(s!==void 0)if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=jS(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=jS(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function AS(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;OS.copy(s),OS.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(OS);return l<n.near||l>n.far?null:{distance:l,point:OS.clone(),object:e}}function jS(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,SS),e.getVertexPosition(c,CS),e.getVertexPosition(l,wS);let u=AS(e,t,n,r,SS,CS,wS,DS);if(u){let e=new Y;Lx.getBarycoord(DS,SS,CS,wS,e),i&&(u.uv=Lx.getInterpolatedAttribute(i,s,c,l,e,new J)),a&&(u.uv1=Lx.getInterpolatedAttribute(a,s,c,l,e,new J)),o&&(u.normal=Lx.getInterpolatedAttribute(o,s,c,l,e,new Y),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new Y,materialIndex:0};Lx.getNormal(SS,CS,wS,t.normal),u.face=t,u.barycoord=e}return u}var MS=class e extends _S{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;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new lS(c,3)),this.setAttribute(`normal`,new lS(l,3)),this.setAttribute(`uv`,new lS(u,2));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 Y;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?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;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};function NS(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(yy(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone():Array.isArray(i)?t[n][r]=i.slice():t[n][r]=i}}return t}function PS(e){let t={};for(let n=0;n<e.length;n++){let r=NS(e[n]);for(let e in r)t[e]=r[e]}return t}function FS(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function IS(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:ab.workingColorSpace}var LS={clone:NS,merge:PS},RS=`void main() {
62
62
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
63
63
  }`,zS=`void main() {
64
64
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
@@ -12823,15 +12823,15 @@ void main() {
12823
12823
  center = quatVec(quat, center) + translate;
12824
12824
  quaternion = quatQuat(quat, quaternion);
12825
12825
  }
12826
- `),new Cb(new Y(-1,-1,-1),new Y(1,1,1)),new Y(-1,-3,1).normalize(),new X(1,1,1),new X(.5,.5,1),new Y(1,1,1),new Cb(new Y(-2,-1,-2),new Y(2,5,2)),new Y(0,-1,0),new X(1,1,1),new X(.25,.25,.5),new Y(.1,1,.1);var _z=class e{static createButton(t,n={}){let r=navigator.xr;if(!r)return null;let i=r,a=document.createElement(`button`);t.xr.enabled=!0,t.xr.setReferenceSpaceType(`local`);function o(){let e=null;async function r(n){console.log(`onSessionStarted`),n.addEventListener(`end`,o),await t.xr.setSession(n),a.textContent=`EXIT VR`,e=n}function o(){console.log(`onSessionEnded`),e?.removeEventListener(`end`,o),a.textContent=`ENTER VR`,e=null}a.style.display=``,a.style.cursor=`pointer`,a.style.left=`calc(50% - 100px)`,a.style.width=`200px`,a.style.height=`100px`,a.textContent=`ENTER VR`;let s={...n,optionalFeatures:[...n.optionalFeatures||[]]};a.onmouseenter=()=>{a.style.opacity=`1.0`},a.onmouseleave=()=>{a.style.opacity=`0.5`},a.onclick=()=>{e===null?(console.log(`requesting session`),i.requestSession(`immersive-vr`,s).then(r)):(console.log(`ending session`),e.end())}}function s(){a.style.display=`none`,a.style.cursor=`auto`,a.style.left=`calc(50% - 75px)`,a.style.width=`150px`,a.onmouseenter=null,a.onmouseleave=null,a.onclick=null}function c(){s(),a.textContent=`VR NOT SUPPORTED`}function l(e){s(),console.warn(`Exception when trying to call xr.isSessionSupported`,e),a.textContent=`VR NOT ALLOWED`}function u(e){e.style.position=`absolute`,e.style.bottom=`20px`,e.style.padding=`12px 6px`,e.style.border=`1px solid #fff`,e.style.borderRadius=`4px`,e.style.background=`rgba(0,0,0,0.1)`,e.style.color=`#fff`,e.style.font=`normal 13px sans-serif`,e.style.textAlign=`center`,e.style.opacity=`0.5`,e.style.outline=`none`,e.style.zIndex=`999`}return a.id=`VRButton`,a.style.display=`none`,u(a),i.isSessionSupported(`immersive-vr`).then(t=>{t?o():c(),t&&e.xrSessionIsGranted&&a.click()}).catch(l),a}static registerSessionGrantedListener(){let t=navigator.xr;if(!t)return null;let n=t;/WebXRViewer\//i.test(navigator.userAgent)||n.addEventListener(`sessiongranted`,()=>{e.xrSessionIsGranted=!0})}};_z.xrSessionIsGranted=!1,_z.registerSessionGrantedListener();var vz=(e=>(e.w=`wrist`,e.t0=`thumb-metacarpal`,e.t1=`thumb-phalanx-proximal`,e.t2=`thumb-phalanx-distal`,e.t3=`thumb-tip`,e.i0=`index-finger-metacarpal`,e.i1=`index-finger-phalanx-proximal`,e.i2=`index-finger-phalanx-intermediate`,e.i3=`index-finger-phalanx-distal`,e.i4=`index-finger-tip`,e.m0=`middle-finger-metacarpal`,e.m1=`middle-finger-phalanx-proximal`,e.m2=`middle-finger-phalanx-intermediate`,e.m3=`middle-finger-phalanx-distal`,e.m4=`middle-finger-tip`,e.r0=`ring-finger-metacarpal`,e.r1=`ring-finger-phalanx-proximal`,e.r2=`ring-finger-phalanx-intermediate`,e.r3=`ring-finger-phalanx-distal`,e.r4=`ring-finger-tip`,e.p0=`pinky-finger-metacarpal`,e.p1=`pinky-finger-phalanx-proximal`,e.p2=`pinky-finger-phalanx-intermediate`,e.p3=`pinky-finger-phalanx-distal`,e.p4=`pinky-finger-tip`,e))(vz||{});Object.keys(vz).length,new Y(0,0,-1),new Y(0,0,1),new Y(-1,0,0),new Y(1,0,0),new Y(0,1,0),new Y(0,-1,0),new Y(0,0,-1),new Y(0,0,1),new Y(-1,0,0),new Y(1,0,0),new Y(0,1,0),new Y(0,-1,0),new Y(0,0,1),new Y(0,0,-1),new Y(0,-1,0),new Y(0,1,0),new Y(-1,0,0),new Y(1,0,0);var yz=Math.PI/180,bz=new Zy().setFromEuler(new ox(Math.PI,0,0));function xz(e,t){let n=t.scale??1,r=t.xOffset??0,i=t.yOffset??0,a=t.zOffset??0,o=(t.roll??0)*yz,s=(t.pitch??0)*yz,c=(t.yaw??0)*yz;e.scale.setScalar(n);let l=new Zy().setFromEuler(new ox(s,c,o));e.quaternion.copy(bz.clone().multiply(l)),e.position.set(r*n,a*n,i*n)}function Sz(e,t,n){let r=new Uint8Array(e),i=new eR({fileBytes:r,fileType:HR(r)});return xz(i,t),n.add(i),i}function Cz(e,t){t.remove(e),e.dispose?.()}function wz(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.`),e}let r=n.count-2,i=[];if(t===2)for(let e=1;e<=r;e++)i.push(n.getX(0)),i.push(n.getX(e)),i.push(n.getX(e+1));else for(let e=0;e<r;e++)e%2==0?(i.push(n.getX(e)),i.push(n.getX(e+1)),i.push(n.getX(e+2))):(i.push(n.getX(e+2)),i.push(n.getX(e+1)),i.push(n.getX(e)));i.length/3!==r&&console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.`);let a=e.clone();return a.setIndex(i),a.clearGroups(),a}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:`,t),e}var Tz=class extends DD{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new jz(e)}),this.register(function(e){return new Mz(e)}),this.register(function(e){return new Vz(e)}),this.register(function(e){return new Hz(e)}),this.register(function(e){return new Uz(e)}),this.register(function(e){return new Pz(e)}),this.register(function(e){return new Fz(e)}),this.register(function(e){return new Iz(e)}),this.register(function(e){return new Lz(e)}),this.register(function(e){return new Az(e)}),this.register(function(e){return new Rz(e)}),this.register(function(e){return new Nz(e)}),this.register(function(e){return new Bz(e)}),this.register(function(e){return new zz(e)}),this.register(function(e){return new Oz(e)}),this.register(function(e){return new Wz(e)}),this.register(function(e){return new Gz(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=aO.extractUrlBase(e);a=aO.resolveURL(t,this.path)}else a=aO.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new AD(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(s.decode(new Uint8Array(e,0,4))===Kz){try{a[Dz.KHR_BINARY_GLTF]=new Yz(e)}catch(e){r&&r(e);return}i=JSON.parse(a[Dz.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new xB(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){let t=this.pluginCallbacks[e](c);t.name||console.error(`THREE.GLTFLoader: Invalid plugin found: missing name`),o[t.name]=t,a[t.name]=!0}if(i.extensionsUsed)for(let e=0;e<i.extensionsUsed.length;++e){let t=i.extensionsUsed[e],n=i.extensionsRequired||[];switch(t){case Dz.KHR_MATERIALS_UNLIT:a[t]=new kz;break;case Dz.KHR_DRACO_MESH_COMPRESSION:a[t]=new Xz(i,this.dracoLoader);break;case Dz.KHR_TEXTURE_TRANSFORM:a[t]=new Zz;break;case Dz.KHR_MESH_QUANTIZATION:a[t]=new Qz;break;default:n.indexOf(t)>=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function Ez(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}var Dz={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},Oz=class{constructor(e){this.parser=e,this.name=Dz.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n=`light:`+e,r=t.cache.get(n);if(r)return r;let i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e],o,s=new X(16777215);a.color!==void 0&&s.setRGB(a.color[0],a.color[1],a.color[2],Rv);let c=a.range===void 0?0:a.range;switch(a.type){case`directional`:o=new $D(s),o.target.position.set(0,0,-1),o.add(o.target);break;case`point`:o=new XD(s),o.distance=c;break;case`spot`:o=new GD(s),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle===void 0?0:a.spot.innerConeAngle,a.spot.outerConeAngle=a.spot.outerConeAngle===void 0?Math.PI/4:a.spot.outerConeAngle,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw Error(`THREE.GLTFLoader: Unexpected light type: `+a.type)}return o.position.set(0,0,0),pB(o,a),a.intensity!==void 0&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||`light_`+e),r=Promise.resolve(o),t.cache.add(n,r),r}getDependency(e,t){if(e===`light`)return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return i===void 0?null:this._loadLight(i).then(function(e){return n._getNodeRef(t.cache,i,e)})}},kz=class{constructor(){this.name=Dz.KHR_MATERIALS_UNLIT}getMaterialType(){return Gx}extendParams(e,t,n){let r=[];e.color=new X(1,1,1),e.opacity=1;let i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){let t=i.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],Rv),e.opacity=t[3]}i.baseColorTexture!==void 0&&r.push(n.assignTexture(e,`map`,i.baseColorTexture,Lv))}return Promise.all(r)}},Az=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}},jz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,`clearcoatMap`,a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,`clearcoatRoughnessMap`,a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,`clearcoatNormalMap`,a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){let e=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new J(e,e)}return Promise.all(i)}},Mz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_DISPERSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name];return t.dispersion=r.dispersion===void 0?0:r.dispersion,Promise.resolve()}},Nz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,`iridescenceMap`,a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,`iridescenceThicknessMap`,a.iridescenceThicknessTexture)),Promise.all(i)}},Pz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_SHEEN}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[];t.sheenColor=new X(0,0,0),t.sheenRoughness=0,t.sheen=1;let a=r.extensions[this.name];if(a.sheenColorFactor!==void 0){let e=a.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],Rv)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,`sheenColorMap`,a.sheenColorTexture,Lv)),a.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,`sheenRoughnessMap`,a.sheenRoughnessTexture)),Promise.all(i)}},Fz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&i.push(n.assignTexture(t,`transmissionMap`,a.transmissionTexture)),Promise.all(i)}},Iz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_VOLUME}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];t.thickness=a.thicknessFactor===void 0?0:a.thicknessFactor,a.thicknessTexture!==void 0&&i.push(n.assignTexture(t,`thicknessMap`,a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;let o=a.attenuationColor||[1,1,1];return t.attenuationColor=new X().setRGB(o[0],o[1],o[2],Rv),Promise.all(i)}},Lz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_IOR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name];return t.ior=r.ior===void 0?1.5:r.ior,Promise.resolve()}},Rz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_SPECULAR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];t.specularIntensity=a.specularFactor===void 0?1:a.specularFactor,a.specularTexture!==void 0&&i.push(n.assignTexture(t,`specularIntensityMap`,a.specularTexture));let o=a.specularColorFactor||[1,1,1];return t.specularColor=new X().setRGB(o[0],o[1],o[2],Rv),a.specularColorTexture!==void 0&&i.push(n.assignTexture(t,`specularColorMap`,a.specularColorTexture,Lv)),Promise.all(i)}},zz=class{constructor(e){this.parser=e,this.name=Dz.EXT_MATERIALS_BUMP}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return t.bumpScale=a.bumpFactor===void 0?1:a.bumpFactor,a.bumpTexture!==void 0&&i.push(n.assignTexture(t,`bumpMap`,a.bumpTexture)),Promise.all(i)}},Bz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,`anisotropyMap`,a.anisotropyTexture)),Promise.all(i)}},Vz=class{constructor(e){this.parser=e,this.name=Dz.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let i=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},Hz=class{constructor(e){this.parser=e,this.name=Dz.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Uz=class{constructor(e){this.parser=e,this.name=Dz.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Wz=class{constructor(e){this.name=Dz.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}else return null}},Gz=class{constructor(e){this.name=Dz.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==nB.TRIANGLES&&e.mode!==nB.TRIANGLE_STRIP&&e.mode!==nB.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new Xb,n=new Y,a=new Zy,s=new Y(1,1,1),c=new JC(e.geometry,e.material,r);for(let e=0;e<r;e++)o.TRANSLATION&&n.fromBufferAttribute(o.TRANSLATION,e),o.ROTATION&&a.fromBufferAttribute(o.ROTATION,e),o.SCALE&&s.fromBufferAttribute(o.SCALE,e),c.setMatrixAt(e,t.compose(n,a,s));for(let t in o)if(t===`_COLOR_0`){let e=o[t];c.instanceColor=new BC(e.array,e.itemSize,e.normalized)}else t!==`TRANSLATION`&&t!==`ROTATION`&&t!==`SCALE`&&e.geometry.setAttribute(t,o[t]);Cx.prototype.copy.call(c,e),this.parser.assignFinalMaterial(c),i.push(c)}return t.isGroup?(t.clear(),t.add(...i),t):i[0]}))}},Kz=`glTF`,qz=12,Jz={JSON:1313821514,BIN:5130562},Yz=class{constructor(e){this.name=Dz.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,qz),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Kz)throw Error(`THREE.GLTFLoader: Unsupported glTF-Binary header.`);if(this.header.version<2)throw Error(`THREE.GLTFLoader: Legacy binary file detected.`);let r=this.header.length-qz,i=new DataView(e,qz),a=0;for(;a<r;){let t=i.getUint32(a,!0);a+=4;let r=i.getUint32(a,!0);if(a+=4,r===Jz.JSON){let r=new Uint8Array(e,qz+a,t);this.content=n.decode(r)}else if(r===Jz.BIN){let n=qz+a;this.body=e.slice(n,n+t)}a+=t}if(this.content===null)throw Error(`THREE.GLTFLoader: JSON content not found.`)}},Xz=class{constructor(e,t){if(!t)throw Error(`THREE.GLTFLoader: No DRACOLoader instance provided.`);this.name=Dz.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,i=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},s={},c={};for(let e in a){let t=sB[e]||e.toLowerCase();o[t]=a[e]}for(let t in e.attributes){let r=sB[t]||t.toLowerCase();if(a[t]!==void 0){let i=n.accessors[e.attributes[t]];c[r]=rB[i.componentType].name,s[r]=i.normalized===!0}}return t.getDependency(`bufferView`,i).then(function(e){return new Promise(function(t,n){r.decodeDracoFile(e,function(e){for(let t in e.attributes){let n=e.attributes[t],r=s[t];r!==void 0&&(n.normalized=r)}t(e)},o,c,Rv,n)})})}},Zz=class{constructor(){this.name=Dz.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0?e:(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e)}},Qz=class{constructor(){this.name=Dz.KHR_MESH_QUANTIZATION}},$z=class extends lD{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let e=0;e!==r;e++)t[e]=n[i+e];return t}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=o*2,c=o*3,l=r-t,u=(n-t)/l,d=u*u,f=d*u,p=e*c,m=p-c,h=-2*f+3*d,g=f-d,_=1-h,v=g-d+u;for(let e=0;e!==o;e++){let t=a[m+e+o],n=a[m+e+s]*l,r=a[p+e+o],c=a[p+e]*l;i[e]=_*t+v*n+h*r+g*c}return i}},eB=new Zy,tB=class extends $z{interpolate_(e,t,n,r){let i=super.interpolate_(e,t,n,r);return eB.fromArray(i).normalize().toArray(i),i}},nB={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},rB={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},iB={9728:u_,9729:h_,9984:d_,9985:g_,9986:p_,9987:v_},aB={33071:c_,33648:l_,10497:s_},oB={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},sB={POSITION:`position`,NORMAL:`normal`,TANGENT:`tangent`,TEXCOORD_0:`uv`,TEXCOORD_1:`uv1`,TEXCOORD_2:`uv2`,TEXCOORD_3:`uv3`,COLOR_0:`color`,WEIGHTS_0:`skinWeight`,JOINTS_0:`skinIndex`},cB={scale:`scale`,translation:`position`,rotation:`quaternion`,weights:`morphTargetInfluences`},lB={CUBICSPLINE:void 0,LINEAR:Ev,STEP:Tv},uB={OPAQUE:`OPAQUE`,MASK:`MASK`,BLEND:`BLEND`};function dB(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new GE({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function fB(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function pB(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function mB(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e<n;e++){let n=t[e];if(n.POSITION!==void 0&&(r=!0),n.NORMAL!==void 0&&(i=!0),n.COLOR_0!==void 0&&(a=!0),r&&i&&a)break}if(!r&&!i&&!a)return Promise.resolve(e);let o=[],s=[],c=[];for(let l=0,u=t.length;l<u;l++){let u=t[l];if(r){let t=u.POSITION===void 0?e.attributes.position:n.getDependency(`accessor`,u.POSITION);o.push(t)}if(i){let t=u.NORMAL===void 0?e.attributes.normal:n.getDependency(`accessor`,u.NORMAL);s.push(t)}if(a){let t=u.COLOR_0===void 0?e.attributes.color:n.getDependency(`accessor`,u.COLOR_0);c.push(t)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(c)]).then(function(t){let n=t[0],o=t[1],s=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=o),a&&(e.morphAttributes.color=s),e.morphTargetsRelative=!0,e})}function hB(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}else console.warn(`THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.`)}}function gB(e){let t,n=e.extensions&&e.extensions[Dz.KHR_DRACO_MESH_COMPRESSION];if(t=n?`draco:`+n.bufferView+`:`+n.indices+`:`+_B(n.attributes):e.indices+`:`+_B(e.attributes)+`:`+e.mode,e.targets!==void 0)for(let n=0,r=e.targets.length;n<r;n++)t+=`:`+_B(e.targets[n]);return t}function _B(e){let t=``,n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+`:`+e[n[r]]+`;`;return t}function vB(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw Error(`THREE.GLTFLoader: Unsupported normalized accessor component type.`)}}function yB(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}var bB=new Xb,xB=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Ez,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>`u`||n&&r<17||i&&a<98?this.textureLoader=new LD(this.options.manager):this.textureLoader=new pO(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new AD(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return fB(i,a,r),pB(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n].joints;for(let t=0,n=r.length;t<n;t++)e[r[t]].isBone=!0}for(let t=0,r=e.length;t<r;t++){let r=e[t];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),i=(e,t)=>{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+ e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){let n=e+`:`+t,r=this.cache.get(n);if(!r){switch(e){case`scene`:r=this.loadScene(t);break;case`node`:r=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case`mesh`:r=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case`accessor`:r=this.loadAccessor(t);break;case`bufferView`:r=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case`buffer`:r=this.loadBuffer(t);break;case`material`:r=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case`texture`:r=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case`skin`:r=this.loadSkin(t);break;case`animation`:r=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case`camera`:r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!r)throw Error(`Unknown type: `+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e===`mesh`?`es`:`s`)]||[];t=Promise.all(r.map(function(t,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!==`arraybuffer`)throw Error(`THREE.GLTFLoader: `+t.type+` buffer type is not supported.`);if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Dz.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(e,i){n.load(aO.resolveURL(t.uri,r.path),e,void 0,function(){i(Error(`THREE.GLTFLoader: Failed to load buffer "`+t.uri+`".`))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency(`buffer`,t.buffer).then(function(e){let n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let e=oB[r.type],t=rB[r.componentType],n=r.normalized===!0,i=new t(r.count*e);return Promise.resolve(new eS(i,e,n))}let i=[];return r.bufferView===void 0?i.push(null):i.push(this.getDependency(`bufferView`,r.bufferView)),r.sparse!==void 0&&(i.push(this.getDependency(`bufferView`,r.sparse.indices.bufferView)),i.push(this.getDependency(`bufferView`,r.sparse.values.bufferView))),Promise.all(i).then(function(e){let i=e[0],a=oB[r.type],o=rB[r.componentType],s=o.BYTES_PER_ELEMENT,c=s*a,l=r.byteOffset||0,u=r.bufferView===void 0?void 0:n.bufferViews[r.bufferView].byteStride,d=r.normalized===!0,f,p;if(u&&u!==c){let e=Math.floor(l/u),n=`InterleavedBuffer:`+r.bufferView+`:`+r.componentType+`:`+e+`:`+r.count,c=t.cache.get(n);c||(f=new o(i,e*u,r.count*u/s),c=new rC(f,u/s),t.cache.add(n,c)),p=new aC(c,a,l%u/s,d)}else f=i===null?new o(r.count*a):new o(i,l,r.count*a),p=new eS(f,a,d);if(r.sparse!==void 0){let t=oB.SCALAR,n=rB[r.sparse.indices.componentType],s=r.sparse.indices.byteOffset||0,c=r.sparse.values.byteOffset||0,l=new n(e[1],s,r.sparse.count*t),u=new o(e[2],c,r.sparse.count*a);i!==null&&(p=new eS(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,t=l.length;e<t;e++){let t=l[e];if(p.setX(t,u[e*a]),a>=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=iB[n.magFilter]||1006,t.minFilter=iB[n.minFilter]||1008,t.wrapS=aB[n.wrapS]||1e3,t.wrapT=aB[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new hb(e);t.needsUpdate=!0,n(t)}),t.load(aO.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),pB(e,a),e.userData.mimeType=a.mimeType||yB(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[Dz.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[Dz.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[Dz.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new zw,Wx.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new Tw,Wx.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return GE}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[Dz.KHR_MATERIALS_UNLIT]){let e=r[Dz.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new X(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],Rv),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,Lv)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||uB.OPAQUE;if(l===uB.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===uB.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==Gx&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new J(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==Gx&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==Gx){let e=i.emissiveFactor;o.emissive=new X().setRGB(e[0],e[1],e[2],Rv)}return i.emissiveTexture!==void 0&&a!==Gx&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,Lv)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),pB(n,i),t.associations.set(n,{materials:e}),i.extensions&&fB(r,n,i),n})}createUniqueName(e){let t=JO.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[Dz.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return CB(n,e,t)})}let a=[];for(let n=0,o=e.length;n<o;n++){let o=e[n],s=gB(o),c=r[s];if(c)a.push(c.promise);else{let e;e=o.extensions&&o.extensions[Dz.KHR_DRACO_MESH_COMPRESSION]?i(o):CB(new _S,o,t),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e].material===void 0?dB(this.cache):this.getDependency(`material`,a[e].material);o.push(t)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(n){let o=n.slice(0,n.length-1),s=n[n.length-1],c=[];for(let n=0,l=s.length;n<l;n++){let l=s[n],u=a[n],d,f=o[n];if(u.mode===nB.TRIANGLES||u.mode===nB.TRIANGLE_STRIP||u.mode===nB.TRIANGLE_FAN||u.mode===void 0)d=i.isSkinnedMesh===!0?new PC(l,f):new kS(l,f),d.isSkinnedMesh===!0&&d.normalizeSkinWeights(),u.mode===nB.TRIANGLE_STRIP?d.geometry=wz(d.geometry,1):u.mode===nB.TRIANGLE_FAN&&(d.geometry=wz(d.geometry,2));else if(u.mode===nB.LINES)d=new Lw(l,f);else if(u.mode===nB.LINE_STRIP)d=new Nw(l,f);else if(u.mode===nB.LINE_LOOP)d=new Rw(l,f);else if(u.mode===nB.POINTS)d=new Ww(l,f);else throw Error(`THREE.GLTFLoader: Primitive mode unsupported: `+u.mode);Object.keys(d.geometry.morphAttributes).length>0&&hB(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),pB(d,i),u.extensions&&fB(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n<r;n++)t.associations.set(c[n],{meshes:e,primitives:n});if(c.length===1)return i.extensions&&fB(r,c[0],i),c[0];let l=new ZS;i.extensions&&fB(r,l,i),t.associations.set(l,{meshes:e});for(let e=0,t=c.length;e<t;e++)l.add(c[e]);return l})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn(`THREE.GLTFLoader: Missing camera parameters.`);return}return n.type===`perspective`?t=new GS(Xy.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type===`orthographic`&&(t=new ZD(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),pB(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let e=0,r=t.joints.length;e<r;e++)n.push(this._loadNodeShallow(t.joints[e]));return t.inverseBindMatrices===void 0?n.push(null):n.push(this.getDependency(`accessor`,t.inverseBindMatrices)),Promise.all(n).then(function(e){let n=e.pop(),r=e,i=[],a=[];for(let e=0,o=r.length;e<o;e++){let o=r[e];if(o){i.push(o);let t=new Xb;n!==null&&t.fromArray(n.array,e*16),a.push(t)}else console.warn(`THREE.GLTFLoader: Joint "%s" could not be found.`,t.joints[e])}return new zC(i,a)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],i=r.name?r.name:`animation_`+e,a=[],o=[],s=[],c=[],l=[];for(let e=0,t=r.channels.length;e<t;e++){let t=r.channels[e],n=r.samplers[t.sampler],i=t.target,u=i.node,d=r.parameters===void 0?n.input:r.parameters[n.input],f=r.parameters===void 0?n.output:r.parameters[n.output];i.node!==void 0&&(a.push(this.getDependency(`node`,u)),o.push(this.getDependency(`accessor`,d)),s.push(this.getDependency(`accessor`,f)),c.push(n),l.push(i))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(s),Promise.all(c),Promise.all(l)]).then(function(e){let t=e[0],a=e[1],o=e[2],s=e[3],c=e[4],l=[];for(let e=0,r=t.length;e<r;e++){let r=t[e],i=a[e],u=o[e],d=s[e],f=c[e];if(r===void 0)continue;r.updateMatrix&&r.updateMatrix();let p=n._createAnimationTracks(r,i,u,d,f);if(p)for(let e=0;e<p.length;e++)l.push(p[e])}let u=new xD(i,void 0,l);return pB(u,r),u})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency(`mesh`,r.mesh).then(function(e){let t=n._getNodeRef(n.meshCache,r.mesh,e);return r.weights!==void 0&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]}),t})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],i=n._loadNodeShallow(e),a=[],o=r.children||[];for(let e=0,t=o.length;e<t;e++)a.push(n.getDependency(`node`,o[e]));let s=r.skin===void 0?Promise.resolve(null):n.getDependency(`skin`,r.skin);return Promise.all([i,Promise.all(a),s]).then(function(e){let t=e[0],n=e[1],r=e[2];r!==null&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(r,bB)});for(let e=0,r=n.length;e<r;e++)t.add(n[e]);return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new FC:t.length>1?new ZS:t.length===1?t[0]:new Cx,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(i.name&&(o.userData.name=i.name,o.name=a),pB(o,i),i.extensions&&fB(n,o,i),i.matrix!==void 0){let e=new Xb;e.fromArray(i.matrix),o.applyMatrix4(e)}else i.translation!==void 0&&o.position.fromArray(i.translation),i.rotation!==void 0&&o.quaternion.fromArray(i.rotation),i.scale!==void 0&&o.scale.fromArray(i.scale);if(!r.associations.has(o))r.associations.set(o,{});else if(i.mesh!==void 0&&r.meshCache.refs[i.mesh]>1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new ZS;n.name&&(i.name=r.createUniqueName(n.name)),pB(i,n),n.extensions&&fB(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e<t;e++)o.push(r.getDependency(`node`,a[e]));return Promise.all(o).then(function(e){for(let t=0,n=e.length;t<n;t++)i.add(e[t]);return r.associations=(e=>{let t=new Map;for(let[e,n]of r.associations)(e instanceof Wx||e instanceof hb)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];cB[i.path]===cB.weights?e.traverse(function(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}):s.push(o);let c;switch(cB[i.path]){case cB.weights:c=gD;break;case cB.rotation:c=vD;break;case cB.translation:case cB.scale:c=bD;break;default:switch(n.itemSize){case 1:c=gD;break;default:c=bD;break}break}let l=r.interpolation===void 0?Ev:lB[r.interpolation],u=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e<n;e++){let n=new c(s[e]+`.`+cB[i.path],t.array,u,l);r.interpolation===`CUBICSPLINE`&&this._createCubicSplineTrackInterpolant(n),a.push(n)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let e=vB(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof vD?tB:$z)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function SB(e,t,n){let r=t.attributes,i=new Cb;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new Y(t[0],t[1],t[2]),new Y(a[0],a[1],a[2])),e.normalized){let t=vB(rB[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new Y,t=new Y;for(let r=0,i=a.length;r<i;r++){let i=a[r];if(i.POSITION!==void 0){let r=n.json.accessors[i.POSITION],a=r.min,o=r.max;if(a!==void 0&&o!==void 0){if(t.setX(Math.max(Math.abs(a[0]),Math.abs(o[0]))),t.setY(Math.max(Math.abs(a[1]),Math.abs(o[1]))),t.setZ(Math.max(Math.abs(a[2]),Math.abs(o[2]))),r.normalized){let e=vB(rB[r.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`)}}i.expandByVector(e)}e.boundingBox=i;let o=new Vb;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,e.boundingSphere=o}function CB(e,t,n){let r=t.attributes,i=[];function a(t,r){return n.getDependency(`accessor`,t).then(function(t){e.setAttribute(r,t)})}for(let t in r){let n=sB[t]||t.toLowerCase();n in e.attributes||i.push(a(r[t],n))}if(t.indices!==void 0&&!e.index){let r=n.getDependency(`accessor`,t.indices).then(function(t){e.setIndex(t)});i.push(r)}return ab.workingColorSpace!==`srgb-linear`&&`COLOR_0`in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ab.workingColorSpace}" not supported.`),pB(e,t),SB(e,t,n),Promise.all(i).then(function(){return t.targets===void 0?e:mB(e,t.targets,n)})}async function wB(e,t){let n=(await new Tz().parseAsync(e,``)).scene;return n.traverse(e=>{e.visible=!1}),t.add(n),n}function TB(e,t){t.remove(e),e.traverse(e=>{let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(e=>e.dispose()):t.material?.dispose()})}var EB=class{constructor(e){this.onPointer=e=>{e.type===`pointerdown`?(this.start(e.clientX,e.clientY),this.mouseDown=!0):e.type===`pointermove`&&this.mouseDown?this.move(e.clientX,e.clientY):e.type===`pointerup`&&this.end()},this.scene=e.scene,this.renderer=e.renderer,this.camera=e.camera,this.container=e.container,this.controls=e.controls,this.draggableBodyIds=e.draggableBodyIds??null,this.mousePos=new J,this.raycaster=new ok,this.raycaster.params.Line.threshold=.1,this.grabDistance=0,this.active=!1,this.mouseDown=!1,this.physicsObject=null,this.localHit=new Y,this.worldHit=new Y,this.currentWorld=new Y,this.offset=new Y,this.arrow=new ZS;let t=new rT(.008,.008,1),n=new GE({color:16737095,transparent:!0,opacity:.5,metalness:0,roughness:.2});this.arrowShaft=new kS(t,n),this.arrowShaft.position.y=.5;let r=new iT(.03,.1);this.arrowHead=new kS(r,n),this.arrowHead.position.y=1,this.arrow.add(this.arrowShaft),this.arrow.add(this.arrowHead),this.arrow.visible=!1,this.scene.add(this.arrow),this.container.addEventListener(`pointerdown`,this.onPointer,!0),document.addEventListener(`pointermove`,this.onPointer,!0),document.addEventListener(`pointerup`,this.onPointer,!0)}updateRaycaster(e,t){let n=this.renderer.domElement.getBoundingClientRect();this.mousePos.x=(e-n.left)/n.width*2-1,this.mousePos.y=-((t-n.top)/n.height)*2+1,this.raycaster.setFromCamera(this.mousePos,this.camera)}start(e,t){this.physicsObject=null,this.updateRaycaster(e,t);let n=this.raycaster.intersectObjects(this.scene.children,!0);for(let e of n){let t=e.object;if(!this.shouldIgnoreForDrag(t)&&this.isDraggableObject(t)){this.physicsObject=t,this.grabDistance=e.distance;let n=this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance);this.localHit.copy(t.worldToLocal(n.clone())),this.worldHit.copy(n),this.currentWorld.copy(n),this.offset.set(0,0,0),this.arrow.position.copy(n),this.arrow.visible=!1,this.active=!0,this.controls.enabled=!1;break}}}setDraggableBodyIds(e){this.draggableBodyIds=e}isDraggableObject(e){if(!(`bodyID`in e)||typeof e.bodyID!=`number`)return!1;let t=e.bodyID;return!(t<=0||this.draggableBodyIds&&!this.draggableBodyIds.has(t))}shouldIgnoreForDrag(e){let t=e;for(;t;){if(t.userData?.ignoreDragForce===!0)return!0;t=t.parent}return!1}move(e,t){this.active&&this.updateRaycaster(e,t)}update(){if(!this.physicsObject||!this.active)return;this.raycaster.setFromCamera(this.mousePos,this.camera),this.currentWorld.copy(this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance)),this.worldHit.copy(this.localHit),this.physicsObject.localToWorld(this.worldHit),this.offset.copy(this.currentWorld).sub(this.worldHit),this.arrow.position.copy(this.worldHit);let e=this.offset.length();if(e>.001){this.arrow.visible=!0;let t=this.offset.clone().normalize();this.arrow.quaternion.setFromUnitVectors(new Y(0,1,0),t);let n=.1,r=Math.max(.01,e-n);this.arrowShaft.scale.y=r,this.arrowShaft.position.y=r/2,this.arrowHead.position.y=r+n/2}else this.arrow.visible=!1}end(){this.physicsObject=null,this.active=!1,this.controls.enabled=!0,this.arrow.visible=!1,this.mouseDown=!1}dispose(){this.container.removeEventListener(`pointerdown`,this.onPointer,!0),document.removeEventListener(`pointermove`,this.onPointer,!0),document.removeEventListener(`pointerup`,this.onPointer,!0),this.arrow.parent&&this.scene.remove(this.arrow),this.arrowShaft.geometry.dispose(),this.arrowHead.geometry.dispose(),this.arrowShaft.material&&this.arrowShaft.material.dispose()}},DB={lookat:[0,0,0],distance:4,elevation:-30,azimuth:45,fovy:45,originType:`AUTO`,enableReflections:!0,enableShadows:!0,height:240,width:320};function OB(e,t,n,r){let i=n*Math.PI/180,a=r*Math.PI/180;return BN([e[0]+t*Math.cos(i)*Math.cos(a),e[1]+t*Math.cos(i)*Math.sin(a),e[2]-t*Math.sin(i)])}function kB(e,t,n,r,i){let a={trackBodyId:null,prevBodyPos:null};n.enabled=!0;let o=e?.lookat??DB.lookat,s=e?.distance??DB.distance,c=e?.elevation??DB.elevation,l=e?.azimuth??DB.azimuth;if(t.fov=e?.fovy??DB.fovy,t.updateProjectionMatrix(),t.position.copy(OB(o,s,c,l)),n.target.copy(BN(o)),n.update(),!e)return a;let u=e.originType??`AUTO`;if(u===`ASSET_BODY`&&e.bodyName&&r){let t=e.bodyName,n=e.entityName,i=n?`${n}/${t}`:null;for(let e=0;e<r.nbody;e++){let n=r.body(e).name;if(n===t||n===i||n.endsWith(`/${t}`)){a.trackBodyId=e;break}}a.trackBodyId===null&&console.warn(`[Camera] bodyName: body "${e.bodyName}" not found.`)}else (u===`AUTO`||u===`ASSET_ROOT`)&&r&&r.nbody>1&&(a.trackBodyId=1);if(a.trackBodyId!==null&&i){let e=BN(i.xpos.slice(a.trackBodyId*3,a.trackBodyId*3+3));t.position.add(e),n.target.add(e),a.prevBodyPos=e,n.update()}return a}function AB(e,t,n,r){if(r.trackBodyId!==null){let i=r.trackBodyId,a=BN(e.xpos.slice(i*3,i*3+3));if(r.prevBodyPos!==null){let e=a.clone().sub(r.prevBodyPos);t.position.add(e),n.target.add(e)}r.prevBodyPos=a}}var jB={},MB=class{constructor(e,t){this.runner=e,this.config=t}},NB={};async function PB(e){let t=new DecompressionStream(`deflate-raw`),n=t.writable.getWriter(),r=t.readable.getReader();n.write(e),n.close();let i=[],a=0;for(;;){let{done:e,value:t}=await r.read();if(e)break;i.push(t),a+=t.byteLength}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function FB(e){let t=[147,78,85,77,80,89];for(let n=0;n<t.length;n++)if(e[n]!==t[n])throw Error(`Invalid .npy magic number`);let n=e[6],r,i;n===1?(r=e[8]|e[9]<<8,i=10):(r=e[8]|e[9]<<8|e[10]<<16|e[11]<<24,i=12);let a=e.slice(i,i+r),o=new TextDecoder().decode(a),s=o.match(/'descr'\s*:\s*'([^']+)'/),c=o.match(/'shape'\s*:\s*\(([^)]*)\)/),l=o.match(/'fortran_order'\s*:\s*(True|False)/);if(!s||!c)throw Error(`Cannot parse .npy header: ${o}`);let u=s[1];if(l&&l[1]===`True`)throw Error(`Fortran-ordered arrays not supported`);let d=c[1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>parseInt(e,10)),f=i+r,p=e.slice(f),m=u[0],h=u.slice(1),g=m===`>`||m===`=`&&!LB(),_;if(h===`f4`)_=new Float32Array(p.buffer,p.byteOffset,p.byteLength/4),g&&(_=RB(_));else if(h===`f8`){let e=new Float64Array(p.buffer,p.byteOffset,p.byteLength/8);g&&(e=zB(e)),_=new Float32Array(e.length);for(let t=0;t<e.length;t++)_[t]=e[t]}else if(h===`i4`){let e=new Int32Array(p.buffer,p.byteOffset,p.byteLength/4);g&&(e=BB(e)),_=new Float32Array(e.length);for(let t=0;t<e.length;t++)_[t]=e[t]}else if(h===`i8`){let e=new BigInt64Array(p.buffer,p.byteOffset,p.byteLength/8);g&&(e=VB(e)),_=new Float32Array(e.length);for(let t=0;t<e.length;t++)_[t]=Number(e[t])}else{let e=u.match(/^S(\d+)$/);if(e){let t=parseInt(e[1],10),n=p.length/t,r=d.reduce((e,t)=>e*t,1);if(n!==r)throw Error(`npz: byte-string array size mismatch (shape ${d} expects ${r} elements, got ${n})`);let i=new TextDecoder(`utf-8`),a=[];for(let e=0;e<n;e++){let n=p.slice(e*t,(e+1)*t),r=n.indexOf(0);a.push(i.decode(r>=0?n.slice(0,r):n))}return{shape:d,data:new Float32Array,strings:a}}let t=h.match(/^U(\d+)$/);if(t){let e=parseInt(t[1],10),n=e*4,r=p.length/n,i=d.reduce((e,t)=>e*t,1);if(r!==i)throw Error(`npz: unicode array size mismatch (shape ${d} expects ${i} elements, got ${r})`);let a=new DataView(p.buffer,p.byteOffset,p.byteLength),o=!g,s=[];for(let t=0;t<r;t++){let r=[];for(let i=0;i<e;i++){let e=a.getUint32(t*n+i*4,o);if(e===0)break;r.push(e)}s.push(String.fromCodePoint(...r))}return{shape:d,data:new Float32Array,strings:s}}throw Error(h===`O`?IB:`Unsupported numpy dtype: ${u}`)}return{shape:d,data:_}}var IB=`npz: pickled python objects (|O dtype) cannot be loaded in the browser`;function LB(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,1,!0),new Int16Array(e)[0]===1}function RB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getFloat32(r*4,!0);return n}function zB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float64Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getFloat64(r*8,!0);return n}function BB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Int32Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getInt32(r*4,!0);return n}function VB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new BigInt64Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getBigInt64(r*8,!0);return n}async function HB(e){let t=new Uint8Array(e),n={},r=0;for(;r+30<=t.length&&!(t[r]!==80||t[r+1]!==75||t[r+2]!==3||t[r+3]!==4);){let e=t[r+8]|t[r+9]<<8,i=(t[r+22]|t[r+23]<<8|t[r+24]<<16|t[r+25]<<24)>>>0,a=(t[r+18]|t[r+19]<<8|t[r+20]<<16|t[r+21]<<24)>>>0,o=t[r+26]|t[r+27]<<8,s=t[r+28]|t[r+29]<<8,c=t.slice(r+30,r+30+o),l=new TextDecoder().decode(c);if(a===4294967295||i===4294967295){let e=r+30+o,n=e;for(;n+4<=e+s;){let e=t[n]|t[n+1]<<8,r=t[n+2]|t[n+3]<<8;if(e===1){let e=n+4;if(i===4294967295&&e+8<=n+4+r&&(e+=8),a===4294967295&&e+8<=n+4+r){let n=(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0;a=((t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0)*4294967296+n}break}n+=4+r}}let u=r+30+o+s,d=t.slice(u,u+a);if(r=u+a,l.endsWith(`/`))continue;l.endsWith(`.npy`)&&(l=l.slice(0,-4));let f;if(e===0)f=d;else if(e===8)f=await PB(d);else{console.warn(`[NPZ] Unsupported compression method ${e} for ${l}`);continue}try{n[l]=FB(f)}catch(e){(e instanceof Error?e.message:String(e))===IB?console.debug(`[NPZ] Skipping pickled object field "${l}"`):console.warn(`[NPZ] Failed to parse ${l}:`,e)}}return n}function UB(e){return typeof e==`function`?e():Promise.resolve(e)}function WB(e){let t=Math.hypot(e[0]??1,e[1]??0,e[2]??0,e[3]??0)||1;return new Float32Array([(e[0]??1)/t,(e[1]??0)/t,(e[2]??0)/t,(e[3]??0)/t])}function GB(e){let t=e.shape[0]??0,n=e.shape.length<=1?1:e.shape.slice(1).reduce((e,t)=>e*t,1),r=[];for(let i=0;i<t;i++){let t=new Float32Array(n),a=i*n;for(let r=0;r<n;r++)t[r]=e.data[a+r]??0;r.push(t)}return r}function KB(e,t){if(!Array.isArray(e)||e.length<2)return t;let n=Number(e[0]),r=Number(e[1]);return!Number.isFinite(n)||!Number.isFinite(r)?t:[n,r]}function qB(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let n of[`x`,`y`,`z`,`roll`,`pitch`,`yaw`]){let r=KB(e[n],[0,0]);(r[0]!==0||r[1]!==0)&&(t[n]=r)}return t}function JB(e){return e?e[0]+Math.random()*(e[1]-e[0]):0}function YB(e,t){let n=e[0]??1,r=e[1]??0,i=e[2]??0,a=e[3]??0,o=t[0]??1,s=t[1]??0,c=t[2]??0,l=t[3]??0;return new Float32Array([n*o-r*s-i*c-a*l,n*s+r*o+i*l-a*c,n*c-r*l+i*o+a*s,n*l+r*c-i*s+a*o])}function XB(e,t,n){let r=Math.cos(e*.5),i=Math.sin(e*.5),a=Math.cos(t*.5),o=Math.sin(t*.5),s=Math.cos(n*.5),c=Math.sin(n*.5);return new Float32Array([r*a*s+i*o*c,i*a*s-r*o*c,r*o*s+i*a*c,r*a*c-i*o*s])}function ZB(e){let t=e.clone();return`transparent`in t&&(t.transparent=!0),`opacity`in t&&(t.opacity=.5),`depthWrite`in t&&(t.depthWrite=!1),`color`in t&&t.color instanceof X&&(t.color=new X(.5,.7,.5)),t}function QB(e){let t=!1;return e.traverse(e=>{e instanceof kS&&(t=!0)}),t}var $B=class{constructor(e,t,n){this.context=n,this.motions=Array.isArray(t.motions)?t.motions:[],this.loadedMotions=new Map,this.sampleHz=50,this.selectedMotionName=this.motions.find(e=>e.default)?.name??this.motions[0]?.name??null,this.selectedMotion=null,this.selectedAnchorBodyIndex=0,this.selectedRootBodyIndex=0,this.datasetQposAdr=[],this.frameAccumulator=0,this.justReset=!0,this.referenceVisible=!0,this.samplingMode=typeof t.sampling_mode==`string`?t.sampling_mode:`start`,this.poseRange=qB(t.pose_range),this.velocityRange=qB(t.velocity_range),this.jointPositionRange=KB(t.joint_position_range,[0,0]),this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.nJoints=this.motions.find(e=>e.name===this.selectedMotionName)?.dataset_joint_names?.length??0,this.ghostBodies=new Map,this.ghostData=n.mjModel?new n.mujoco.MjData(n.mjModel):null,this.ghostRoot=this.createGhostRoot(),this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[]}getCommand(){if(!this.selectedMotion||this.refLen===0)return new Float32Array(this.nJoints*2);if(this.selectedMotion.clip_format===`qpos`)return new Float32Array;let e=this.refJointPos[this.refIdx]??new Float32Array(this.nJoints),t=this.selectedMotion.jointVel[this.refIdx]??new Float32Array(this.nJoints),n=new Float32Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}getUiConfig(){return null}async setSelectedMotion(e){if(e===null)return this.selectedMotionName=null,this.selectedMotion=null,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[],this.refLen=0,this.nJoints=0,this.updateGhostPose(),!1;let t=this.motions.find(t=>t.name===e);if(!t)return!1;let n=this.loadedMotions.get(e)??await this.loadMotion(t);return this.loadedMotions.set(e,n),this.selectedMotionName=e,this.selectedMotion=n,this.selectedAnchorBodyIndex=Math.max(0,n.body_names.indexOf(n.anchor_body_name)),this.selectedRootBodyIndex=0,this.datasetQposAdr=this.resolveQposAdr(n.dataset_joint_names??[]),this.refLen=n.frameCount,this.refJointPos=n.jointPos,this.refIdx=this.sampleInitialFrame(this.refLen),this.nJoints=n.jointPos[0]?.length??0,this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose(),!0}setReferenceVisible(e){this.referenceVisible=e,this.ghostRoot&&(this.ghostRoot.visible=e&&this.selectedMotion!==null)}reset(){this.refIdx=this.sampleInitialFrame(this.refLen),this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose()}update(e){if(!this.selectedMotion||this.refLen<=1)return;if(this.justReset){this.justReset=!1,this.updateGhostPose();return}if(this.selectedMotion.time_source===`sim`){let e=this.context.mjData?.time??0;this.refIdx=this.sampleHz>0?Math.floor(e*this.sampleHz)%this.refLen:0,this.updateGhostPose();return}let t=this.selectedMotion?.loop!==!1;this.frameAccumulator+=e*this.sampleHz;let n=!1;for(;this.frameAccumulator>=1;){if(this.refIdx+=1,this.refIdx>=this.refLen){if(!t){this.refIdx=this.refLen-1,this.frameAccumulator=0;break}this.refIdx=0,n=!0}--this.frameAccumulator}n&&this.context.requestReset?.(),this.updateGhostPose()}updateDebugVisuals(){this.ghostRoot&&(this.ghostRoot.visible=this.referenceVisible&&this.selectedMotion!==null)}dispose(){this.ghostRoot&&(this.ghostRoot.parent?.remove(this.ghostRoot),this.ghostRoot.traverse(e=>{if(e instanceof kS)if(Array.isArray(e.material))for(let t of e.material)t.dispose?.();else e.material?.dispose?.()})),this.ghostData?.delete?.()}isReady(){return this.selectedMotion!==null&&this.refLen>0}getSelectedMotion(){return this.selectedMotion}getSelectedMotionName(){return this.selectedMotionName}getAnchorBodyName(){return this.selectedMotion?.anchor_body_name??this.motions.find(e=>e.name===this.selectedMotionName)?.anchor_body_name??null}getBodyNames(){return this.selectedMotion?.body_names??this.motions.find(e=>e.name===this.selectedMotionName)?.body_names??[]}getAnchorBodyIndex(){return this.selectedAnchorBodyIndex}getAnchorPos(e=this.refIdx){if(!this.selectedMotion)return null;let t=this.refBodyPosW[e];if(!t)return null;let n=this.selectedAnchorBodyIndex*3;return t.slice(n,n+3)}getAnchorQuat(e=this.refIdx){if(!this.selectedMotion)return null;let t=this.refBodyQuatW[e];if(!t)return null;let n=this.selectedAnchorBodyIndex*4;return WB(t.slice(n,n+4))}getBodyPosW(e=this.refIdx){if(!this.selectedMotion)return null;let t=this.refBodyPosW[e];return t?t.slice():null}createGhostRoot(){let e=this.context.bodies??null,t=this.context.mjModel;if(!e||!t)return null;let n=new ZS;n.name=`Tracking Ghost`,n.visible=!1;for(let[t,r]of Object.entries(e)){let e=Number(t);if(!this.isDynamicBody(e))continue;let i=r.clone(!0);i.traverse(e=>{e instanceof kS&&(Array.isArray(e.material)?e.material=e.material.map(ZB):e.material=ZB(e.material),e.renderOrder=2)}),QB(i)&&(this.ghostBodies.set(e,i),n.add(i))}return(this.context.mujocoRoot??this.context.scene).add(n),n}isDynamicBody(e){let t=this.context.mjModel;if(!t||e<=0||e>=t.nbody)return!1;let n=e;for(;n>0;){if(t.body_jntnum[n]>0)return!0;n=t.body_parentid[n]}return!1}async loadMotion(e){this.sampleHz=e.fps;let t=await HB(await UB(e.data)),n=[];if(e.clip_format===`qpos`){if(!t.qpos)throw Error(`Motion asset with clip_format='qpos' is missing 'qpos'`);let r=GB(t.qpos);return{...e,jointPos:n,jointVel:n,bodyPosW:n,bodyQuatW:n,bodyLinVelW:n,bodyAngVelW:n,qposFrames:r,frameCount:r.length}}for(let e of[`joint_pos`,`joint_vel`,`body_pos_w`,`body_quat_w`,`body_lin_vel_w`,`body_ang_vel_w`])if(!t[e])throw Error(`Motion asset is missing '${e}'`);let r=GB(t.joint_pos),i=GB(t.joint_vel),a=t.body_names?.strings??null,o=this.selectMotionBodyFrames(GB(t.body_pos_w),e.body_names,3,a),s=this.selectMotionBodyFrames(GB(t.body_quat_w),e.body_names,4,a),c=this.selectMotionBodyFrames(GB(t.body_lin_vel_w),e.body_names,3,a),l=this.selectMotionBodyFrames(GB(t.body_ang_vel_w),e.body_names,3,a);return{...e,jointPos:r,jointVel:i,bodyPosW:o,bodyQuatW:s,bodyLinVelW:c,bodyAngVelW:l,frameCount:r.length}}selectMotionBodyFrames(e,t,n,r=null){let i=this.context.mjModel,a=e[0];if(!i||!a||t.length===0)return e;let o=Math.floor(a.length/n);if(o===t.length)return e;let s;if(r!==null)s=t.map(e=>r.indexOf(e));else{let e=this.findBodyIdByName(t[0]);s=t.map(e=>this.findBodyIdByName(e)).map(t=>t-e)}return s.some(e=>e<0||e>=o)?(console.warn(`[TrackingCommand] Could not map all motion body names to source body indices; using raw body frames.`),e):e.map(e=>{let r=new Float32Array(t.length*n);for(let t=0;t<s.length;t++){let i=s[t]*n,a=t*n;for(let t=0;t<n;t++)r[a+t]=e[i+t]??0}return r})}updateReferenceState(){let e=this.selectedMotion;if(!e||e.frameCount===0||e.clip_format===`qpos`){this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[];return}this.refBodyPosW=e.bodyPosW.map(e=>e.slice()),this.refBodyQuatW=e.bodyQuatW.map(e=>e.slice()),this.refBodyLinVelW=e.bodyLinVelW.map(e=>e.slice()),this.refBodyAngVelW=e.bodyAngVelW.map(e=>e.slice()),this.refRootPos=this.refBodyPosW.map(e=>e.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3)),this.refRootQuat=this.refBodyQuatW.map(e=>WB(e.slice(this.selectedRootBodyIndex*4,this.selectedRootBodyIndex*4+4)))}applyReferenceStateToSim(){let e=this.context.mjModel,t=this.context.mjData,n=this.selectedMotion;if(!e||!t||!n||this.refLen===0||n.clip_format===`qpos`)return;let r=this.sampleRootPos(this.refIdx),i=this.sampleRootQuat(this.refIdx),a=this.findFreeJointIndex();if(r&&i&&a>=0){let n=e.jnt_qposadr[a],o=e.jnt_dofadr[a];t.qpos[n+0]=r[0]??0,t.qpos[n+1]=r[1]??0,t.qpos[n+2]=r[2]??0,t.qpos[n+3]=i[0]??1,t.qpos[n+4]=i[1]??0,t.qpos[n+5]=i[2]??0,t.qpos[n+6]=i[3]??0;let s=this.sampleRootVelocity(this.refIdx,this.refBodyLinVelW),c=this.sampleRootAngularVelocity(this.refIdx);s&&c&&(t.qvel[o+0]=s[0]??0,t.qvel[o+1]=s[1]??0,t.qvel[o+2]=s[2]??0,t.qvel[o+3]=c[0]??0,t.qvel[o+4]=c[1]??0,t.qvel[o+5]=c[2]??0)}let o=this.sampleJointPos(this.refIdx),s=n.jointVel[this.refIdx]??new Float32Array;for(let e=0;e<this.datasetQposAdr.length&&e<o.length;e++)t.qpos[this.datasetQposAdr[e]]=o[e]??0;for(let e=0;e<this.datasetQposAdr.length&&e<s.length;e++){let n=this.resolveQvelAdrForQposAdr(this.datasetQposAdr[e]);n>=0&&(t.qvel[n]=s[e]??0)}this.context.mujoco.mj_forward(e,t)}sampleRootPos(e){let t=this.refRootPos[e];if(!t)return null;let n=t.slice();return n[0]+=JB(this.poseRange.x),n[1]+=JB(this.poseRange.y),n[2]+=JB(this.poseRange.z),n}sampleRootQuat(e){let t=this.refRootQuat[e];if(!t)return null;let n=JB(this.poseRange.roll),r=JB(this.poseRange.pitch),i=JB(this.poseRange.yaw);return n===0&&r===0&&i===0?t:WB(YB(XB(n,r,i),t))}sampleRootVelocity(e,t){let n=t[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return n?(n[0]+=JB(this.velocityRange.x),n[1]+=JB(this.velocityRange.y),n[2]+=JB(this.velocityRange.z),n):null}sampleRootAngularVelocity(e){let t=this.refBodyAngVelW[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return t?(t[0]+=JB(this.velocityRange.roll),t[1]+=JB(this.velocityRange.pitch),t[2]+=JB(this.velocityRange.yaw),t):null}sampleInitialFrame(e){return e<=1||this.samplingMode===`start`?0:this.samplingMode===`uniform`?Math.floor(Math.random()*e):0}sampleJointPos(e){let t=this.refJointPos[e]??new Float32Array;if(this.jointPositionRange[0]===0&&this.jointPositionRange[1]===0)return t;let n=t.slice();for(let e=0;e<n.length;e++)n[e]+=JB(this.jointPositionRange);return n}resolveQposAdr(e){let t=this.context.mjModel;if(!t||e.length===0)return[];let n=[];for(let r of e){let e=-1;for(let n=0;n<t.njnt;n++){let i=t.jnt(n).name;if(i===r||i.endsWith(`/${r}`)){e=t.jnt_qposadr[n];break}}e>=0&&n.push(e)}return n}resolveQvelAdrForQposAdr(e){let t=this.context.mjModel;if(!t)return-1;for(let n=0;n<t.njnt;n++)if(t.jnt_qposadr[n]===e)return t.jnt_dofadr[n];return-1}findBodyIdByName(e){let t=this.context.mjModel;if(!t)return-1;for(let n=0;n<t.nbody;n++){let r=t.body(n).name;if(r===e||r.endsWith(`/${e}`))return n}return-1}updateGhostPose(){if(!this.ghostRoot||!this.ghostData||!this.context.mjModel||!this.selectedMotion||!this.refLen){this.ghostRoot&&(this.ghostRoot.visible=!1);return}if(this.selectedMotion.clip_format===`qpos`&&this.selectedMotion.qposFrames){let e=this.selectedMotion.qposFrames[this.refIdx];e&&this.ghostData.qpos.set(e),this.context.mujoco.mj_forward(this.context.mjModel,this.ghostData);for(let[e,t]of this.ghostBodies)aP(this.ghostData.xpos,e,t.position),oP(this.ghostData.xquat,e,t.quaternion);this.ghostRoot.visible=this.referenceVisible;return}let e=this.ghostData.qpos;e.set(this.context.mjModel.qpos0);let t=this.refRootPos[this.refIdx],n=this.refRootQuat[this.refIdx],r=this.findFreeJointIndex();if(r>=0&&t&&n){let i=this.context.mjModel.jnt_qposadr[r];e[i+0]=t[0]??0,e[i+1]=t[1]??0,e[i+2]=t[2]??0,e[i+3]=n[0]??1,e[i+4]=n[1]??0,e[i+5]=n[2]??0,e[i+6]=n[3]??0}let i=this.refJointPos[this.refIdx]??new Float32Array;for(let t=0;t<this.datasetQposAdr.length&&t<i.length;t++)e[this.datasetQposAdr[t]]=i[t]??0;this.context.mujoco.mj_forward(this.context.mjModel,this.ghostData);for(let[e,t]of this.ghostBodies)aP(this.ghostData.xpos,e,t.position),oP(this.ghostData.xquat,e,t.quaternion);this.ghostRoot.visible=this.referenceVisible}findFreeJointIndex(){let e=this.context.mjModel;if(!e)return-1;for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}};function eV(e,t){return`${e}:${t}`}function tV(e){return typeof e==`object`&&!!e&&`isReady`in e&&`getAnchorBodyName`in e&&`getBodyNames`in e}var nV={UiCommand:class{constructor(e,t){this.inputs=Array.isArray(t.ui?.inputs)?t.ui.inputs:[],this.values=new Map;for(let e of this.inputs)e.type===`slider`?this.values.set(e.name,e.default):e.type===`checkbox`&&this.values.set(e.name,+!!e.default)}getCommand(){let e=this.inputs.filter(e=>e.type===`slider`||e.type===`checkbox`),t=new Float32Array(e.length);for(let n=0;n<e.length;n++){let r=e[n],i=r.type===`checkbox`?+!!r.default:r.default;t[n]=this.values.get(r.name)??i??0}return t}getUiConfig(){return{inputs:this.inputs}}reset(){for(let e of this.inputs)e.type===`slider`?this.values.set(e.name,e.default):e.type===`checkbox`&&this.values.set(e.name,+!!e.default)}setValue(e,t){let n=this.inputs.find(t=>(t.type===`slider`||t.type===`checkbox`)&&t.name===e);if(!n)return 0;if(n.type===`checkbox`){let e=+(t>=.5);return this.values.set(n.name,e),e}let r=Math.max(n.min,Math.min(n.max,t));return this.values.set(n.name,r),r}},TrackingCommand:$B},rV=class{constructor(){this.terms=new Map,this.commands=new Map,this.commandGroups=new Map,this.values=new Map,this.listeners=new Set,this.context=null}initialize(e,t,n){this.clear(),this.context=t;let r={...nV,...NB,...n};for(let[n,i]of Object.entries(e)){let e=r[i.name];if(!e)throw Error(`Unknown command term: ${i.name}`);let a=new e(n,i,t);this.terms.set(n,a),this.registerUi(n,a)}}update(e){for(let t of this.terms.values())t.update?.(e)}updateDebugVisuals(){for(let e of this.terms.values())e.updateDebugVisuals?.()}resetTerms(){for(let e of this.terms.values())e.reset?.();this.syncValuesFromTerms(),this.emit({type:`reset`,commandId:`*`})}getCommandGroups(){return Array.from(this.commandGroups.keys())}getCommandsInGroup(e){return(this.commandGroups.get(e)??[]).map(e=>this.commands.get(e)).filter(Boolean)}getCommands(){return Array.from(this.commands.values())}getCommandById(e){return this.commands.get(e)}getValue(e){return this.values.get(e)??0}getValues(){let e={};for(let[t,n]of this.values)e[t]=n;return e}getCommand(e){let t=this.terms.get(e);return t?t.getCommand():new Float32Array}getTerm(e){return this.terms.get(e)}getContext(){return this.context}getVelocityCommand(){return this.terms.has(`velocity`)?this.getCommand(`velocity`):this.terms.has(`twist`)?this.getCommand(`twist`):new Float32Array([.5,0,0])}setValue(e,t){let n=this.commands.get(e);if(!n||n.config.type!==`slider`&&n.config.type!==`checkbox`)return;let r=this.terms.get(n.groupName),i=n.config.name,a=r?.setValue?r.setValue(i,t):void 0,o=typeof a==`number`?a:t;this.values.set(e,o),this.emit({type:`change`,commandId:e,groupName:n.groupName,value:o})}triggerButton(e){let t=this.commands.get(e);!t||t.config.type!==`button`||(this.terms.get(t.groupName)?.triggerButton?.(t.config.name),this.emit({type:`button`,commandId:e,groupName:t.groupName}))}resetToDefaults(){this.resetTerms()}addEventListener(e){this.listeners.add(e)}removeEventListener(e){this.listeners.delete(e)}clear(){for(let e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.context=null,this.emit({type:`clear`,commandId:``})}hasCommands(){return this.commands.size>0}dispose(){for(let e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.listeners.clear(),this.context=null}registerUi(e,t){let n=t.getUiConfig?.(),r=Array.isArray(n?.inputs)?n.inputs:[];if(r.length!==0){this.commandGroups.set(e,[]);for(let n of r){let i=eV(e,n.name);if(this.commands.set(i,{id:i,groupName:e,config:n}),this.commandGroups.get(e).push(i),n.type===`slider`||n.type===`checkbox`){let e=t.getCommand(),a=r.filter(e=>e.type===`slider`||e.type===`checkbox`).findIndex(e=>e.name===n.name),o=n.type===`checkbox`?+!!n.default:n.default;this.values.set(i,e[a]??o)}}this.emit({type:`group_registered`,commandId:e,groupName:e})}}syncValuesFromTerms(){for(let[e,t]of this.commands){if(t.config.type!==`slider`&&t.config.type!==`checkbox`)continue;let n=this.terms.get(t.groupName);if(!n)continue;let r=(n.getUiConfig?.()?.inputs??[]).filter(e=>e.type===`slider`||e.type===`checkbox`).findIndex(e=>e.name===t.config.name);if(r>=0){let t=n.getCommand();this.values.set(e,t[r]??this.values.get(e)??0)}}}emit(e){for(let t of this.listeners)try{t(e)}catch(e){console.warn(`[CommandManager] Listener error:`,e)}}};function iV(e){let t=e[0]??1,n=e[1]??0,r=e[2]??0,i=e[3]??0,a=Math.hypot(t,n,r,i);if(a<1e-9)return[1,0,0,0];let o=1/a;return[t*o,n*o,r*o,i*o]}function aV(e,t){let n=e[0]??1,r=e[1]??0,i=e[2]??0,a=e[3]??0,o=t[0]??1,s=t[1]??0,c=t[2]??0,l=t[3]??0;return[n*o-r*s-i*c-a*l,n*s+r*o+i*l-a*c,n*c-r*l+i*o+a*s,n*l+r*c-i*s+a*o]}function oV(e){let t=e[0]??1,n=e[1]??0,r=e[2]??0,i=e[3]??0,a=t*t+n*n+r*r+i*i;if(a<1e-9)return[1,0,0,0];let o=1/a;return[t*o,-n*o,-r*o,-i*o]}function sV(e,t){let n=e[0]??1,r=e[1]??0,i=e[2]??0,a=e[3]??0,o=t[0]??0,s=t[1]??0,c=t[2]??0,l=2*(i*c-a*s),u=2*(a*o-r*c),d=2*(r*s-i*o),f=i*d-a*u,p=a*l-r*d,m=r*u-i*l;return[o-n*l+f,s-n*u+p,c-n*d+m]}function cV(e){let[t,n,r,i]=iV(e),a=n*n,o=r*r,s=i*i,c=n*r,l=n*i,u=r*i,d=t*n,f=t*r,p=t*i;return[1-2*(o+s),2*(c-p),2*(c+p),1-2*(a+s),2*(l-f),2*(u+d)]}function lV(e,t=0){return typeof e==`number`?e:e instanceof Float32Array?e[t]??0:typeof e==`boolean`?+!!e:0}function uV(e){return e instanceof Float32Array?e:typeof e==`number`?new Float32Array([e]):new Float32Array}function dV(e,t){let n=e.getContext()?.mjModel??null;if(!n)return-1;for(let e=0;e<n.nbody;e++){let r=n.body(e).name;if(r===t||r.endsWith(`/${t}`))return e}return-1}function fV(e){let t=e.runner.getContext()?.commandManager?.getTerm(`motion`);return tV(t)&&t.isReady()?t:null}function pV(e,t,n){let r=new Uint8Array(e.names),i=new TextDecoder,a=[];for(let e=0;e<t;e++){let t=n[e],o=t;for(;o<r.length&&r[o]!==0;)o++;a.push(i.decode(r.subarray(t,o)))}return a}function mV(e){return pV(e,e.njnt,e.name_jntadr)}function hV(e,t){let n=e.getContext()?.mjModel??null;if(!n)return t.map(()=>-1);let r=mV(n);return t.map(e=>{let t=r.indexOf(e);return t<0?-1:n.jnt_qposadr[t]})}function gV(e,t){let n=e.getContext()?.mjModel??null;if(!n)return t.map(()=>-1);let r=mV(n);return t.map(e=>{let t=r.indexOf(e);return t<0?-1:n.jnt_dofadr[t]})}function _V(e,t){let n=e.getContext()?.mjModel??null;return n?pV(n,n.nsite,n.name_siteadr).indexOf(t):-1}function vV(e,t){let n=e.getContext()?.mjModel??null;if(!n)return{adr:0,dim:0};let r=pV(n,n.nsensor,n.name_sensoradr).indexOf(t);return r<0?{adr:0,dim:0}:{adr:n.sensor_adr[r],dim:n.sensor_dim[r]}}function yV(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:null}var bV={Const:(e,t)=>Number(t.value??0),StepCount:(e,t,n,r)=>{let i=(r.count??0)+1;return r.count=i,i},Param:(e,t,n)=>{let r=n.params[String(t.name)];return typeof r==`number`?r:Array.isArray(r)?Float32Array.from(r):0},RootAngVelB:(e,t,n)=>n.state.rootAngVel?new Float32Array(n.state.rootAngVel):new Float32Array(3),RootLinkLinVelB:(e,t,n)=>n.state.rootLinVel?new Float32Array(n.state.rootLinVel):new Float32Array(3),RootLinkPosW:(e,t,n)=>n.state.rootPos?new Float32Array(n.state.rootPos):new Float32Array(3),RootLinkQuatW:(e,t,n)=>n.state.rootQuat?new Float32Array(n.state.rootQuat):new Float32Array([1,0,0,0]),ProjectedGravityB:(e,t,n)=>{let r=n.state.rootQuat??new Float32Array([1,0,0,0]),i=r[0],a=r[1],o=r[2],s=r[3],c=2*(o*-1-s*0),l=2*(s*0-a*-1),u=2*(a*0-o*0),d=o*u-s*l,f=s*c-a*u,p=a*l-o*c;return new Float32Array([0-i*c+d,0-i*l+f,-1-i*u+p])},Add:e=>CV(e[0],e[1],(e,t)=>e+t),Sub:e=>CV(e[0],e[1],(e,t)=>e-t),Mul:e=>CV(e[0],e[1],(e,t)=>e*t),Neg:e=>SV(e[0],e=>-e),Abs:e=>SV(e[0],Math.abs),Acos:e=>SV(e[0],e=>Math.acos(Math.max(-1,Math.min(1,e)))),Index:(e,t)=>uV(e[0])[Number(t.i??0)]??0,Gt:e=>wV(e[0],e[1],(e,t)=>e>t),Lt:e=>wV(e[0],e[1],(e,t)=>e<t),Ge:e=>wV(e[0],e[1],(e,t)=>e>=t),Le:e=>wV(e[0],e[1],(e,t)=>e<=t),Any:e=>TV(e[0],(e,t)=>e||t,!1),All:e=>TV(e[0],(e,t)=>e&&t,!0),Or:e=>xV(e[0],e[1],(e,t)=>e||t),And:e=>xV(e[0],e[1],(e,t)=>e&&t),Not:e=>{let t=e[0];if(typeof t==`boolean`)return!t;if(typeof t==`number`)return t===0;if(t instanceof Uint8Array){let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=+!t[n];return e}return!1},ConstVec:(e,t)=>{let n=Array.isArray(t.values)?t.values:[];return Float32Array.from(n)},SpawnCapture:(e,t,n,r)=>(r.captured===void 0&&(r.captured=uV(e[0]).slice()),r.captured),QuatApplyInv:e=>Float32Array.from(sV(uV(e[0]),uV(e[1]))),TrackingAnchorPos:(e,t,n)=>{let r=fV(n)?.getAnchorPos()??null;return r?new Float32Array(r):new Float32Array(3)},TrackingAnchorQuat:(e,t,n)=>{let r=fV(n)?.getAnchorQuat()??null;return r?new Float32Array(r):new Float32Array([1,0,0,0])},TrackingCurrentAnchorPos:(e,t,n)=>{let r=fV(n)?.getAnchorBodyName()??null,i=n.runner.getContext()?.mjData??null;if(!r||!i)return new Float32Array(3);let a=dV(n.runner,r);return a<0?new Float32Array(3):new Float32Array([i.xpos[a*3],i.xpos[a*3+1],i.xpos[a*3+2]])},TrackingCurrentAnchorQuat:(e,t,n)=>{let r=fV(n)?.getAnchorBodyName()??null,i=n.runner.getContext()?.mjData??null;if(!r||!i)return new Float32Array([1,0,0,0]);let a=dV(n.runner,r);return a<0?new Float32Array([1,0,0,0]):new Float32Array(i.xquat.slice(a*4,a*4+4))},TrackingBodyPosZDeviationMax:(e,t,n)=>{let r=fV(n),i=n.runner.getContext()?.mjData??null;if(!r||!i)return 0;let a=r.getBodyPosW();if(!a)return 0;let o=r.getBodyNames(),s=Array.isArray(t.body_names)&&t.body_names.length>0?t.body_names:o,c=0;for(let e of s){let t=o.indexOf(e),r=dV(n.runner,e);if(t<0||r<0)continue;let s=a[t*3+2]??0,l=i.xpos[r*3+2]??0,u=Math.abs(s-l);u>c&&(c=u)}return c},Clip:(e,t)=>{let n=Number(t.min??-1/0),r=Number(t.max??1/0);return SV(e[0],e=>Math.min(r,Math.max(n,e)))},History:(e,t,n,r)=>{let i=Math.max(1,Math.floor(Number(t.steps??1))),a=uV(e[0]),o=r.buffer;if(o===void 0||o.length!==i||o[0].length!==a.length)o=Array.from({length:i},()=>a.slice()),r.buffer=o;else{for(let e=o.length-1;e>0;e--)o[e].set(o[e-1]);o[0].set(a)}if(i===1)return new Float32Array(o[0]);let s=a.length,c=new Float32Array(s*i);if(t.interleaved)for(let e=0;e<s;e++)for(let t=0;t<i;t++)c[e*i+t]=o[t][e];else for(let e=0;e<i;e++)c.set(o[e],e*s);return c},Concat:e=>{let t=0,n=e.map(e=>uV(e));for(let e of n)t+=e.length;let r=new Float32Array(t),i=0;for(let e of n)r.set(e,i),i+=e.length;return r},Cos:e=>SV(e[0],Math.cos),Sin:e=>SV(e[0],Math.sin),QuatMul:e=>Float32Array.from(aV(uV(e[0]),uV(e[1]))),QuatInv:e=>Float32Array.from(oV(uV(e[0]))),QuatToRot6d:e=>Float32Array.from(cV(uV(e[0]))),JointPos:(e,t,n)=>{let r=yV(t.joint_names);if(r===null){let e=n.state.jointPos;return e?new Float32Array(e):new Float32Array(n.runner.getNumActions())}let i=hV(n.runner,r),a=n.runner.getContext()?.mjData?.qpos,o=new Float32Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]>=0&&a!==void 0?a[i[e]]:0;return o},DefaultJointPos:(e,t,n)=>{let r=yV(t.joint_names);if(r===null)return new Float32Array(n.runner.getDefaultJointPos());let i=hV(n.runner,r),a=n.runner.getContext()?.mjModel?.qpos0,o=new Float32Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]>=0&&a!==void 0?a[i[e]]:0;return o},JointVel:(e,t,n)=>{let r=yV(t.joint_names);if(r===null){let e=n.state.jointVel;return e?new Float32Array(e):new Float32Array(n.runner.getNumActions())}let i=gV(n.runner,r),a=n.runner.getContext()?.mjData?.qvel,o=new Float32Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]>=0&&a!==void 0?a[i[e]]:0;return o},PrevAction:(e,t,n)=>new Float32Array(n.runner.getLastActions()),CommandValue:(e,t,n)=>{let r=String(t.command??``),i=r?n.runner.getContext()?.commandManager?.getCommand(r):null;return i?new Float32Array(i):new Float32Array},Sensor:(e,t,n)=>{let{adr:r,dim:i}=vV(n.runner,String(t.sensor??``)),a=n.runner.getContext()?.mjData?.sensordata,o=new Float32Array(i);if(a!==void 0)for(let e=0;e<i;e++)o[e]=a[r+e]??0;return o},SitePos:(e,t,n)=>{let r=_V(n.runner,String(t.site??``)),i=n.runner.getContext()?.mjData?.site_xpos;return r<0||i===void 0?new Float32Array(3):new Float32Array([i[r*3],i[r*3+1],i[r*3+2]])},BodyPos:(e,t,n)=>{let r=dV(n.runner,String(t.body??``)),i=n.runner.getContext()?.mjData?.xpos;return r<0||i===void 0?new Float32Array(3):new Float32Array([i[r*3],i[r*3+1],i[r*3+2]])},BodyQuat:(e,t,n)=>{let r=dV(n.runner,String(t.body??``)),i=n.runner.getContext()?.mjData?.xquat;return r<0||i===void 0?new Float32Array([1,0,0,0]):new Float32Array(i.slice(r*4,r*4+4))},TrackingRefBodyPos:(e,t,n)=>{let r=fV(n);if(!r)return new Float32Array(3);let i=r.getBodyPosW();if(!i)return new Float32Array(3);let a=r.getBodyNames().indexOf(String(t.body??``));return a<0?new Float32Array(3):new Float32Array([i[a*3],i[a*3+1],i[a*3+2]])}};function xV(e,t,n){let r=(e,t)=>typeof e==`boolean`?e:typeof e==`number`?e!==0:e instanceof Uint8Array||e instanceof Float32Array?(e[t]??0)!==0:!1,i=e instanceof Uint8Array||e instanceof Float32Array,a=t instanceof Uint8Array||t instanceof Float32Array;if(!i&&!a)return n(r(e,0),r(t,0));let o=i?e.length:1,s=a?t.length:1,c=Math.max(o,s),l=new Uint8Array(c);for(let i=0;i<c;i++)l[i]=+!!n(r(e,i),r(t,i));return l}function SV(e,t){if(typeof e==`number`)return t(e);if(e instanceof Float32Array){let n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=t(e[r]);return n}return t(lV(e))}function CV(e,t,n){let r=e instanceof Float32Array,i=t instanceof Float32Array;if(!r&&!i)return n(lV(e),lV(t));let a=Math.max(r?e.length:1,i?t.length:1),o=new Float32Array(a);for(let s=0;s<a;s++)o[s]=n(r?e[s]??0:lV(e),i?t[s]??0:lV(t));return o}function wV(e,t,n){let r=e instanceof Float32Array,i=t instanceof Float32Array;if(!r&&!i)return n(lV(e),lV(t));let a=Math.max(r?e.length:1,i?t.length:1),o=new Uint8Array(a);for(let s=0;s<a;s++)o[s]=+!!n(r?e[s]??0:lV(e),i?t[s]??0:lV(t));return o}function TV(e,t,n){if(typeof e==`boolean`)return e;if(typeof e==`number`)return e!==0;let r=n;if(e instanceof Uint8Array){for(let n=0;n<e.length;n++)r=t(r,e[n]!==0);return r}if(e instanceof Float32Array){for(let n=0;n<e.length;n++)r=t(r,e[n]!==0);return r}return r}var EV=class{constructor(){this.states=new Map}get(e){let t=this.states.get(e);return t===void 0&&(t={},this.states.set(e,t)),t}reset(){this.states.clear()}};function DV(e,t,n){let r={};for(let i of e.nodes){let e=bV[i.op];if(e===void 0)throw Error(`DSL interpreter: unknown primitive op "${i.op}". Add it to the engine's primitive registry, or fix the build's serializer.`);let a=(i.in??[]).map(e=>{if(!(e in r))throw Error(`DSL interpreter: node "${i.out}" references unresolved input "${e}". Graph nodes must appear in topological order.`);return r[e]});r[i.out]=e(a,i.attrs??{},t,n.get(i.out))}let i=r[e.output];if(i===void 0)throw Error(`DSL interpreter: graph output "${e.output}" was not produced by any node.`);return i}var OV=class extends MB{constructor(e,t){super(e,t),this.store=new EV,this.graph=t.graph,this.params=t.params??{}}evaluate(e){let t=DV(this.graph,{runner:this.runner,state:e,params:this.params},this.store);return typeof t==`boolean`?t:typeof t==`number`?t!==0:!1}reset(){this.store.reset()}};function kV(e){return`kind`in e&&e.kind===`termination`}var AV=class{constructor(e,t,n){this.terms=[];for(let[r,i]of Object.entries(e)){if(kV(i)){let e={name:r,params:i.params,time_out:i.time_out,graph:{kind:`termination`,nodes:i.nodes,output:i.output}};this.terms.push({name:r,term:new OV(n,e),isTimeOut:i.time_out??!1});continue}let e=t[i.name];if(!e){console.warn(`[TerminationManager] Unknown termination type: ${i.name}`);continue}let a={name:i.name,params:i.params,time_out:i.time_out};this.terms.push({name:r,term:new e(n,a),isTimeOut:i.time_out??!1})}}evaluate(e){let t=!1,n=!1,r=[];for(let{name:i,term:a,isTimeOut:o}of this.terms)a.evaluate(e)&&(r.push(i),o?n=!0:t=!0);return{done:t||n,terminated:t,truncated:n,reasons:r}}reset(){for(let{term:e}of this.terms)e.reset?.()}get size(){return this.terms.length}},jV={},MV=Object.defineProperty,NV=Object.getOwnPropertyDescriptor,PV=Object.getOwnPropertyNames,FV=Object.prototype.hasOwnProperty,IV=(e=>typeof n<`u`?n:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof n<`u`?n:e)[t]}):e)(function(e){if(typeof n<`u`)return n.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),Z=(e,t)=>()=>(e&&(t=e(e=0)),t),LV=(e,t)=>{for(var n in t)MV(e,n,{get:t[n],enumerable:!0})},RV=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of PV(t))!FV.call(e,i)&&i!==n&&MV(e,i,{get:()=>t[i],enumerable:!(r=NV(t,i))||r.enumerable});return e},zV=e=>RV(MV({},`__esModule`,{value:!0}),e),BV,VV,HV,UV,WV,GV=Z(()=>{BV=new Map,VV=[],HV=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=BV.get(e);if(r===void 0)BV.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=VV.indexOf(e);t!==-1&&VV.splice(t,1);for(let t=0;t<VV.length;t++)if(BV.get(VV[t]).priority<=n){VV.splice(t,0,e);return}VV.push(e)}return}throw TypeError(`not a valid backend`)},UV=async e=>{let t=BV.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}}},WV=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?VV:n,i,a=[],o=new Set;for(let e of r){let t=await UV(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)})]}}),KV=Z(()=>{GV()}),qV,JV=Z(()=>{qV=`1.24.3`}),YV,XV,ZV=Z(()=>{JV(),YV=`warning`,XV={wasm:{},webgl:{},webgpu:{},versions:{common:qV},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}`);YV=e}},get logLevel(){return YV}},Object.defineProperty(XV,"logLevel",{enumerable:!0})}),QV,$V=Z(()=>{ZV(),QV=XV}),eH,tH,nH=Z(()=>{eH=(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<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}else throw Error(`Can not access image data`)},tH=(e,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<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),rH,iH,aH,oH,sH,cH,lH=Z(()=>{yH(),rH=(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<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new vH(`float32`,u,[1,4,n,r]):new vH(`float32`,u,[1,3,n,r])},iH=async(e,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,rH(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(rH(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return rH(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},aH=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new vH({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},oH=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new vH({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},sH=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new vH({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},cH=(e,t,n)=>new vH({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),uH,dH,fH,pH,mH=Z(()=>{uH=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),dH=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),fH=!1,pH=()=>{if(!fH){fH=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(uH.set(`int64`,BigInt64Array),dH.set(BigInt64Array,`int64`)),t&&(uH.set(`uint64`,BigUint64Array),dH.set(BigUint64Array,`uint64`)),r?(uH.set(`float16`,n),dH.set(n,`float16`)):uH.set(`float16`,Uint16Array)}}}),hH,gH,_H=Z(()=>{yH(),hH=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},gH=(e,t)=>{switch(e.location){case`cpu`:return new vH(e.type,e.data,t);case`cpu-pinned`:return new vH({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new vH({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new vH({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new vH({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),vH,yH=Z(()=>{nH(),lH(),mH(),_H(),vH=class{constructor(e,t,n){pH();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=uH.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=uH.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=dH.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=hH(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 iH(e,t)}static fromTexture(e,t){return aH(e,t)}static fromGpuBuffer(e,t){return oH(e,t)}static fromMLTensor(e,t){return sH(e,t)}static fromPinnedBuffer(e,t,n){return cH(e,t,n)}toDataURL(e){return eH(this,e)}toImageData(e){return tH(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 gH(this,e)}}}),bH,xH=Z(()=>{yH(),bH=vH}),SH,CH,wH,TH,EH,DH,OH=Z(()=>{ZV(),SH=(e,t)=>{(typeof XV.trace>`u`?!XV.wasm.trace:!XV.trace)||console.timeStamp(`${e}::ORT::${t}`)},CH=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),SH(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},wH=e=>{(typeof XV.trace>`u`?!XV.wasm.trace:!XV.trace)||CH(`BEGIN`,e)},TH=e=>{(typeof XV.trace>`u`?!XV.wasm.trace:!XV.trace)||CH(`END`,e)},EH=e=>{(typeof XV.trace>`u`?!XV.wasm.trace:!XV.trace)||console.time(`ORT::${e}`)},DH=e=>{(typeof XV.trace>`u`?!XV.wasm.trace:!XV.trace)||console.timeEnd(`ORT::${e}`)}}),kH,AH=Z(()=>{GV(),xH(),OH(),kH=class e{constructor(e){this.handler=e}async run(e,t,n){wH(),EH(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof bH||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 bH)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 bH)&&(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 bH?s[e]=t:s[e]=new bH(t.type,t.data,t.dims)}return DH(`InferenceSession.run`),TH(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){wH(),EH(`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 WV(o),l=await s.createInferenceSessionHandler(a,c);return DH(`InferenceSession.create`),TH(),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}}}),jH,MH=Z(()=>{AH(),jH=kH}),NH=Z(()=>{}),PH=Z(()=>{}),FH=Z(()=>{}),IH=Z(()=>{});LV({},{InferenceSession:()=>jH,TRACE:()=>SH,TRACE_EVENT_BEGIN:()=>EH,TRACE_EVENT_END:()=>DH,TRACE_FUNC_BEGIN:()=>wH,TRACE_FUNC_END:()=>TH,Tensor:()=>bH,env:()=>QV,registerBackend:()=>HV});var LH=Z(()=>{KV(),$V(),MH(),xH(),NH(),PH(),OH(),FH(),IH()}),RH=Z(()=>{}),zH={};LV(zH,{default:()=>HH});var BH,VH,HH,UH=Z(()=>{h$(),yU(),lU(),BH=`ort-wasm-proxy-worker`,VH=globalThis.self?.name===BH,VH&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:_U(n.wasm).then(()=>{r$(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;i$(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=c$(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;l$(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:u$(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;f$(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},m$([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:p$(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),HH=VH?null:e=>new Worker(e??QH,{type:`module`,name:BH})}),WH={};LV(WH,{default:()=>KH});async function GH(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.Zc||=new Map).set(e,n)},t.unmountExternalData=()=>{delete t.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,ae:!0}).buffer.constructor;let a=e=>async(...n)=>{try{if(t.$c)throw Error(`Session already started`);let r=t.$c={Nd:n[0],errors:[]},i=await e(...n);if(t.$c!==r)throw Error(`Session mismatch`);t.gd?.flush();let a=r.errors;if(0<a.length){let e=await Promise.all(a);if(e=e.filter(e=>e),0<e.length)throw Error(e.join(`
12826
+ `),new Cb(new Y(-1,-1,-1),new Y(1,1,1)),new Y(-1,-3,1).normalize(),new X(1,1,1),new X(.5,.5,1),new Y(1,1,1),new Cb(new Y(-2,-1,-2),new Y(2,5,2)),new Y(0,-1,0),new X(1,1,1),new X(.25,.25,.5),new Y(.1,1,.1);var _z=class e{static createButton(t,n={}){let r=navigator.xr;if(!r)return null;let i=r,a=document.createElement(`button`);t.xr.enabled=!0,t.xr.setReferenceSpaceType(`local`);function o(){let e=null;async function r(n){console.log(`onSessionStarted`),n.addEventListener(`end`,o),await t.xr.setSession(n),a.textContent=`EXIT VR`,e=n}function o(){console.log(`onSessionEnded`),e?.removeEventListener(`end`,o),a.textContent=`ENTER VR`,e=null}a.style.display=``,a.style.cursor=`pointer`,a.style.left=`calc(50% - 100px)`,a.style.width=`200px`,a.style.height=`100px`,a.textContent=`ENTER VR`;let s={...n,optionalFeatures:[...n.optionalFeatures||[]]};a.onmouseenter=()=>{a.style.opacity=`1.0`},a.onmouseleave=()=>{a.style.opacity=`0.5`},a.onclick=()=>{e===null?(console.log(`requesting session`),i.requestSession(`immersive-vr`,s).then(r)):(console.log(`ending session`),e.end())}}function s(){a.style.display=`none`,a.style.cursor=`auto`,a.style.left=`calc(50% - 75px)`,a.style.width=`150px`,a.onmouseenter=null,a.onmouseleave=null,a.onclick=null}function c(){s(),a.textContent=`VR NOT SUPPORTED`}function l(e){s(),console.warn(`Exception when trying to call xr.isSessionSupported`,e),a.textContent=`VR NOT ALLOWED`}function u(e){e.style.position=`absolute`,e.style.bottom=`20px`,e.style.padding=`12px 6px`,e.style.border=`1px solid #fff`,e.style.borderRadius=`4px`,e.style.background=`rgba(0,0,0,0.1)`,e.style.color=`#fff`,e.style.font=`normal 13px sans-serif`,e.style.textAlign=`center`,e.style.opacity=`0.5`,e.style.outline=`none`,e.style.zIndex=`999`}return a.id=`VRButton`,a.style.display=`none`,u(a),i.isSessionSupported(`immersive-vr`).then(t=>{t?o():c(),t&&e.xrSessionIsGranted&&a.click()}).catch(l),a}static registerSessionGrantedListener(){let t=navigator.xr;if(!t)return null;let n=t;/WebXRViewer\//i.test(navigator.userAgent)||n.addEventListener(`sessiongranted`,()=>{e.xrSessionIsGranted=!0})}};_z.xrSessionIsGranted=!1,_z.registerSessionGrantedListener();var vz=(e=>(e.w=`wrist`,e.t0=`thumb-metacarpal`,e.t1=`thumb-phalanx-proximal`,e.t2=`thumb-phalanx-distal`,e.t3=`thumb-tip`,e.i0=`index-finger-metacarpal`,e.i1=`index-finger-phalanx-proximal`,e.i2=`index-finger-phalanx-intermediate`,e.i3=`index-finger-phalanx-distal`,e.i4=`index-finger-tip`,e.m0=`middle-finger-metacarpal`,e.m1=`middle-finger-phalanx-proximal`,e.m2=`middle-finger-phalanx-intermediate`,e.m3=`middle-finger-phalanx-distal`,e.m4=`middle-finger-tip`,e.r0=`ring-finger-metacarpal`,e.r1=`ring-finger-phalanx-proximal`,e.r2=`ring-finger-phalanx-intermediate`,e.r3=`ring-finger-phalanx-distal`,e.r4=`ring-finger-tip`,e.p0=`pinky-finger-metacarpal`,e.p1=`pinky-finger-phalanx-proximal`,e.p2=`pinky-finger-phalanx-intermediate`,e.p3=`pinky-finger-phalanx-distal`,e.p4=`pinky-finger-tip`,e))(vz||{});Object.keys(vz).length,new Y(0,0,-1),new Y(0,0,1),new Y(-1,0,0),new Y(1,0,0),new Y(0,1,0),new Y(0,-1,0),new Y(0,0,-1),new Y(0,0,1),new Y(-1,0,0),new Y(1,0,0),new Y(0,1,0),new Y(0,-1,0),new Y(0,0,1),new Y(0,0,-1),new Y(0,-1,0),new Y(0,1,0),new Y(-1,0,0),new Y(1,0,0);var yz=Math.PI/180,bz=new Zy().setFromEuler(new ox(Math.PI,0,0));function xz(e,t){let n=t.scale??1,r=t.xOffset??0,i=t.yOffset??0,a=t.zOffset??0,o=(t.roll??0)*yz,s=(t.pitch??0)*yz,c=(t.yaw??0)*yz;e.scale.setScalar(n);let l=new Zy().setFromEuler(new ox(s,c,o));e.quaternion.copy(bz.clone().multiply(l)),e.position.set(r*n,a*n,i*n)}function Sz(e,t,n){let r=new Uint8Array(e),i=new eR({fileBytes:r,fileType:HR(r)});return xz(i,t),n.add(i),i}function Cz(e,t){t.remove(e),e.dispose?.()}function wz(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.`),e}let r=n.count-2,i=[];if(t===2)for(let e=1;e<=r;e++)i.push(n.getX(0)),i.push(n.getX(e)),i.push(n.getX(e+1));else for(let e=0;e<r;e++)e%2==0?(i.push(n.getX(e)),i.push(n.getX(e+1)),i.push(n.getX(e+2))):(i.push(n.getX(e+2)),i.push(n.getX(e+1)),i.push(n.getX(e)));i.length/3!==r&&console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.`);let a=e.clone();return a.setIndex(i),a.clearGroups(),a}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:`,t),e}var Tz=class extends DD{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new jz(e)}),this.register(function(e){return new Mz(e)}),this.register(function(e){return new Vz(e)}),this.register(function(e){return new Hz(e)}),this.register(function(e){return new Uz(e)}),this.register(function(e){return new Pz(e)}),this.register(function(e){return new Fz(e)}),this.register(function(e){return new Iz(e)}),this.register(function(e){return new Lz(e)}),this.register(function(e){return new Az(e)}),this.register(function(e){return new Rz(e)}),this.register(function(e){return new Nz(e)}),this.register(function(e){return new Bz(e)}),this.register(function(e){return new zz(e)}),this.register(function(e){return new Oz(e)}),this.register(function(e){return new Wz(e)}),this.register(function(e){return new Gz(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=aO.extractUrlBase(e);a=aO.resolveURL(t,this.path)}else a=aO.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new AD(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(s.decode(new Uint8Array(e,0,4))===Kz){try{a[Dz.KHR_BINARY_GLTF]=new Yz(e)}catch(e){r&&r(e);return}i=JSON.parse(a[Dz.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new xB(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){let t=this.pluginCallbacks[e](c);t.name||console.error(`THREE.GLTFLoader: Invalid plugin found: missing name`),o[t.name]=t,a[t.name]=!0}if(i.extensionsUsed)for(let e=0;e<i.extensionsUsed.length;++e){let t=i.extensionsUsed[e],n=i.extensionsRequired||[];switch(t){case Dz.KHR_MATERIALS_UNLIT:a[t]=new kz;break;case Dz.KHR_DRACO_MESH_COMPRESSION:a[t]=new Xz(i,this.dracoLoader);break;case Dz.KHR_TEXTURE_TRANSFORM:a[t]=new Zz;break;case Dz.KHR_MESH_QUANTIZATION:a[t]=new Qz;break;default:n.indexOf(t)>=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function Ez(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}var Dz={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},Oz=class{constructor(e){this.parser=e,this.name=Dz.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n=`light:`+e,r=t.cache.get(n);if(r)return r;let i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e],o,s=new X(16777215);a.color!==void 0&&s.setRGB(a.color[0],a.color[1],a.color[2],Rv);let c=a.range===void 0?0:a.range;switch(a.type){case`directional`:o=new $D(s),o.target.position.set(0,0,-1),o.add(o.target);break;case`point`:o=new XD(s),o.distance=c;break;case`spot`:o=new GD(s),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle===void 0?0:a.spot.innerConeAngle,a.spot.outerConeAngle=a.spot.outerConeAngle===void 0?Math.PI/4:a.spot.outerConeAngle,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw Error(`THREE.GLTFLoader: Unexpected light type: `+a.type)}return o.position.set(0,0,0),pB(o,a),a.intensity!==void 0&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||`light_`+e),r=Promise.resolve(o),t.cache.add(n,r),r}getDependency(e,t){if(e===`light`)return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return i===void 0?null:this._loadLight(i).then(function(e){return n._getNodeRef(t.cache,i,e)})}},kz=class{constructor(){this.name=Dz.KHR_MATERIALS_UNLIT}getMaterialType(){return Gx}extendParams(e,t,n){let r=[];e.color=new X(1,1,1),e.opacity=1;let i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){let t=i.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],Rv),e.opacity=t[3]}i.baseColorTexture!==void 0&&r.push(n.assignTexture(e,`map`,i.baseColorTexture,Lv))}return Promise.all(r)}},Az=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}},jz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,`clearcoatMap`,a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,`clearcoatRoughnessMap`,a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,`clearcoatNormalMap`,a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){let e=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new J(e,e)}return Promise.all(i)}},Mz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_DISPERSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name];return t.dispersion=r.dispersion===void 0?0:r.dispersion,Promise.resolve()}},Nz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,`iridescenceMap`,a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,`iridescenceThicknessMap`,a.iridescenceThicknessTexture)),Promise.all(i)}},Pz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_SHEEN}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[];t.sheenColor=new X(0,0,0),t.sheenRoughness=0,t.sheen=1;let a=r.extensions[this.name];if(a.sheenColorFactor!==void 0){let e=a.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],Rv)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,`sheenColorMap`,a.sheenColorTexture,Lv)),a.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,`sheenRoughnessMap`,a.sheenRoughnessTexture)),Promise.all(i)}},Fz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&i.push(n.assignTexture(t,`transmissionMap`,a.transmissionTexture)),Promise.all(i)}},Iz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_VOLUME}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];t.thickness=a.thicknessFactor===void 0?0:a.thicknessFactor,a.thicknessTexture!==void 0&&i.push(n.assignTexture(t,`thicknessMap`,a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;let o=a.attenuationColor||[1,1,1];return t.attenuationColor=new X().setRGB(o[0],o[1],o[2],Rv),Promise.all(i)}},Lz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_IOR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name];return t.ior=r.ior===void 0?1.5:r.ior,Promise.resolve()}},Rz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_SPECULAR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];t.specularIntensity=a.specularFactor===void 0?1:a.specularFactor,a.specularTexture!==void 0&&i.push(n.assignTexture(t,`specularIntensityMap`,a.specularTexture));let o=a.specularColorFactor||[1,1,1];return t.specularColor=new X().setRGB(o[0],o[1],o[2],Rv),a.specularColorTexture!==void 0&&i.push(n.assignTexture(t,`specularColorMap`,a.specularColorTexture,Lv)),Promise.all(i)}},zz=class{constructor(e){this.parser=e,this.name=Dz.EXT_MATERIALS_BUMP}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return t.bumpScale=a.bumpFactor===void 0?1:a.bumpFactor,a.bumpTexture!==void 0&&i.push(n.assignTexture(t,`bumpMap`,a.bumpTexture)),Promise.all(i)}},Bz=class{constructor(e){this.parser=e,this.name=Dz.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:KE}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,`anisotropyMap`,a.anisotropyTexture)),Promise.all(i)}},Vz=class{constructor(e){this.parser=e,this.name=Dz.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let i=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},Hz=class{constructor(e){this.parser=e,this.name=Dz.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Uz=class{constructor(e){this.parser=e,this.name=Dz.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Wz=class{constructor(e){this.name=Dz.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}else return null}},Gz=class{constructor(e){this.name=Dz.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==nB.TRIANGLES&&e.mode!==nB.TRIANGLE_STRIP&&e.mode!==nB.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new Xb,n=new Y,a=new Zy,s=new Y(1,1,1),c=new JC(e.geometry,e.material,r);for(let e=0;e<r;e++)o.TRANSLATION&&n.fromBufferAttribute(o.TRANSLATION,e),o.ROTATION&&a.fromBufferAttribute(o.ROTATION,e),o.SCALE&&s.fromBufferAttribute(o.SCALE,e),c.setMatrixAt(e,t.compose(n,a,s));for(let t in o)if(t===`_COLOR_0`){let e=o[t];c.instanceColor=new BC(e.array,e.itemSize,e.normalized)}else t!==`TRANSLATION`&&t!==`ROTATION`&&t!==`SCALE`&&e.geometry.setAttribute(t,o[t]);Cx.prototype.copy.call(c,e),this.parser.assignFinalMaterial(c),i.push(c)}return t.isGroup?(t.clear(),t.add(...i),t):i[0]}))}},Kz=`glTF`,qz=12,Jz={JSON:1313821514,BIN:5130562},Yz=class{constructor(e){this.name=Dz.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,qz),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Kz)throw Error(`THREE.GLTFLoader: Unsupported glTF-Binary header.`);if(this.header.version<2)throw Error(`THREE.GLTFLoader: Legacy binary file detected.`);let r=this.header.length-qz,i=new DataView(e,qz),a=0;for(;a<r;){let t=i.getUint32(a,!0);a+=4;let r=i.getUint32(a,!0);if(a+=4,r===Jz.JSON){let r=new Uint8Array(e,qz+a,t);this.content=n.decode(r)}else if(r===Jz.BIN){let n=qz+a;this.body=e.slice(n,n+t)}a+=t}if(this.content===null)throw Error(`THREE.GLTFLoader: JSON content not found.`)}},Xz=class{constructor(e,t){if(!t)throw Error(`THREE.GLTFLoader: No DRACOLoader instance provided.`);this.name=Dz.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,i=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},s={},c={};for(let e in a){let t=sB[e]||e.toLowerCase();o[t]=a[e]}for(let t in e.attributes){let r=sB[t]||t.toLowerCase();if(a[t]!==void 0){let i=n.accessors[e.attributes[t]];c[r]=rB[i.componentType].name,s[r]=i.normalized===!0}}return t.getDependency(`bufferView`,i).then(function(e){return new Promise(function(t,n){r.decodeDracoFile(e,function(e){for(let t in e.attributes){let n=e.attributes[t],r=s[t];r!==void 0&&(n.normalized=r)}t(e)},o,c,Rv,n)})})}},Zz=class{constructor(){this.name=Dz.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0?e:(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e)}},Qz=class{constructor(){this.name=Dz.KHR_MESH_QUANTIZATION}},$z=class extends lD{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let e=0;e!==r;e++)t[e]=n[i+e];return t}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=o*2,c=o*3,l=r-t,u=(n-t)/l,d=u*u,f=d*u,p=e*c,m=p-c,h=-2*f+3*d,g=f-d,_=1-h,v=g-d+u;for(let e=0;e!==o;e++){let t=a[m+e+o],n=a[m+e+s]*l,r=a[p+e+o],c=a[p+e]*l;i[e]=_*t+v*n+h*r+g*c}return i}},eB=new Zy,tB=class extends $z{interpolate_(e,t,n,r){let i=super.interpolate_(e,t,n,r);return eB.fromArray(i).normalize().toArray(i),i}},nB={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},rB={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},iB={9728:u_,9729:h_,9984:d_,9985:g_,9986:p_,9987:v_},aB={33071:c_,33648:l_,10497:s_},oB={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},sB={POSITION:`position`,NORMAL:`normal`,TANGENT:`tangent`,TEXCOORD_0:`uv`,TEXCOORD_1:`uv1`,TEXCOORD_2:`uv2`,TEXCOORD_3:`uv3`,COLOR_0:`color`,WEIGHTS_0:`skinWeight`,JOINTS_0:`skinIndex`},cB={scale:`scale`,translation:`position`,rotation:`quaternion`,weights:`morphTargetInfluences`},lB={CUBICSPLINE:void 0,LINEAR:Ev,STEP:Tv},uB={OPAQUE:`OPAQUE`,MASK:`MASK`,BLEND:`BLEND`};function dB(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new GE({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function fB(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function pB(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function mB(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e<n;e++){let n=t[e];if(n.POSITION!==void 0&&(r=!0),n.NORMAL!==void 0&&(i=!0),n.COLOR_0!==void 0&&(a=!0),r&&i&&a)break}if(!r&&!i&&!a)return Promise.resolve(e);let o=[],s=[],c=[];for(let l=0,u=t.length;l<u;l++){let u=t[l];if(r){let t=u.POSITION===void 0?e.attributes.position:n.getDependency(`accessor`,u.POSITION);o.push(t)}if(i){let t=u.NORMAL===void 0?e.attributes.normal:n.getDependency(`accessor`,u.NORMAL);s.push(t)}if(a){let t=u.COLOR_0===void 0?e.attributes.color:n.getDependency(`accessor`,u.COLOR_0);c.push(t)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(c)]).then(function(t){let n=t[0],o=t[1],s=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=o),a&&(e.morphAttributes.color=s),e.morphTargetsRelative=!0,e})}function hB(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}else console.warn(`THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.`)}}function gB(e){let t,n=e.extensions&&e.extensions[Dz.KHR_DRACO_MESH_COMPRESSION];if(t=n?`draco:`+n.bufferView+`:`+n.indices+`:`+_B(n.attributes):e.indices+`:`+_B(e.attributes)+`:`+e.mode,e.targets!==void 0)for(let n=0,r=e.targets.length;n<r;n++)t+=`:`+_B(e.targets[n]);return t}function _B(e){let t=``,n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+`:`+e[n[r]]+`;`;return t}function vB(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw Error(`THREE.GLTFLoader: Unsupported normalized accessor component type.`)}}function yB(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}var bB=new Xb,xB=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Ez,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>`u`||n&&r<17||i&&a<98?this.textureLoader=new LD(this.options.manager):this.textureLoader=new pO(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new AD(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return fB(i,a,r),pB(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n].joints;for(let t=0,n=r.length;t<n;t++)e[r[t]].isBone=!0}for(let t=0,r=e.length;t<r;t++){let r=e[t];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),i=(e,t)=>{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+ e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){let n=e+`:`+t,r=this.cache.get(n);if(!r){switch(e){case`scene`:r=this.loadScene(t);break;case`node`:r=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case`mesh`:r=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case`accessor`:r=this.loadAccessor(t);break;case`bufferView`:r=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case`buffer`:r=this.loadBuffer(t);break;case`material`:r=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case`texture`:r=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case`skin`:r=this.loadSkin(t);break;case`animation`:r=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case`camera`:r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!r)throw Error(`Unknown type: `+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e===`mesh`?`es`:`s`)]||[];t=Promise.all(r.map(function(t,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!==`arraybuffer`)throw Error(`THREE.GLTFLoader: `+t.type+` buffer type is not supported.`);if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Dz.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(e,i){n.load(aO.resolveURL(t.uri,r.path),e,void 0,function(){i(Error(`THREE.GLTFLoader: Failed to load buffer "`+t.uri+`".`))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency(`buffer`,t.buffer).then(function(e){let n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let e=oB[r.type],t=rB[r.componentType],n=r.normalized===!0,i=new t(r.count*e);return Promise.resolve(new eS(i,e,n))}let i=[];return r.bufferView===void 0?i.push(null):i.push(this.getDependency(`bufferView`,r.bufferView)),r.sparse!==void 0&&(i.push(this.getDependency(`bufferView`,r.sparse.indices.bufferView)),i.push(this.getDependency(`bufferView`,r.sparse.values.bufferView))),Promise.all(i).then(function(e){let i=e[0],a=oB[r.type],o=rB[r.componentType],s=o.BYTES_PER_ELEMENT,c=s*a,l=r.byteOffset||0,u=r.bufferView===void 0?void 0:n.bufferViews[r.bufferView].byteStride,d=r.normalized===!0,f,p;if(u&&u!==c){let e=Math.floor(l/u),n=`InterleavedBuffer:`+r.bufferView+`:`+r.componentType+`:`+e+`:`+r.count,c=t.cache.get(n);c||(f=new o(i,e*u,r.count*u/s),c=new rC(f,u/s),t.cache.add(n,c)),p=new aC(c,a,l%u/s,d)}else f=i===null?new o(r.count*a):new o(i,l,r.count*a),p=new eS(f,a,d);if(r.sparse!==void 0){let t=oB.SCALAR,n=rB[r.sparse.indices.componentType],s=r.sparse.indices.byteOffset||0,c=r.sparse.values.byteOffset||0,l=new n(e[1],s,r.sparse.count*t),u=new o(e[2],c,r.sparse.count*a);i!==null&&(p=new eS(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,t=l.length;e<t;e++){let t=l[e];if(p.setX(t,u[e*a]),a>=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=iB[n.magFilter]||1006,t.minFilter=iB[n.minFilter]||1008,t.wrapS=aB[n.wrapS]||1e3,t.wrapT=aB[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new hb(e);t.needsUpdate=!0,n(t)}),t.load(aO.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),pB(e,a),e.userData.mimeType=a.mimeType||yB(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[Dz.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[Dz.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[Dz.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new zw,Wx.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new Tw,Wx.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return GE}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[Dz.KHR_MATERIALS_UNLIT]){let e=r[Dz.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new X(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],Rv),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,Lv)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||uB.OPAQUE;if(l===uB.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===uB.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==Gx&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new J(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==Gx&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==Gx){let e=i.emissiveFactor;o.emissive=new X().setRGB(e[0],e[1],e[2],Rv)}return i.emissiveTexture!==void 0&&a!==Gx&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,Lv)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),pB(n,i),t.associations.set(n,{materials:e}),i.extensions&&fB(r,n,i),n})}createUniqueName(e){let t=JO.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[Dz.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return CB(n,e,t)})}let a=[];for(let n=0,o=e.length;n<o;n++){let o=e[n],s=gB(o),c=r[s];if(c)a.push(c.promise);else{let e;e=o.extensions&&o.extensions[Dz.KHR_DRACO_MESH_COMPRESSION]?i(o):CB(new _S,o,t),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e].material===void 0?dB(this.cache):this.getDependency(`material`,a[e].material);o.push(t)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(n){let o=n.slice(0,n.length-1),s=n[n.length-1],c=[];for(let n=0,l=s.length;n<l;n++){let l=s[n],u=a[n],d,f=o[n];if(u.mode===nB.TRIANGLES||u.mode===nB.TRIANGLE_STRIP||u.mode===nB.TRIANGLE_FAN||u.mode===void 0)d=i.isSkinnedMesh===!0?new PC(l,f):new kS(l,f),d.isSkinnedMesh===!0&&d.normalizeSkinWeights(),u.mode===nB.TRIANGLE_STRIP?d.geometry=wz(d.geometry,1):u.mode===nB.TRIANGLE_FAN&&(d.geometry=wz(d.geometry,2));else if(u.mode===nB.LINES)d=new Lw(l,f);else if(u.mode===nB.LINE_STRIP)d=new Nw(l,f);else if(u.mode===nB.LINE_LOOP)d=new Rw(l,f);else if(u.mode===nB.POINTS)d=new Ww(l,f);else throw Error(`THREE.GLTFLoader: Primitive mode unsupported: `+u.mode);Object.keys(d.geometry.morphAttributes).length>0&&hB(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),pB(d,i),u.extensions&&fB(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n<r;n++)t.associations.set(c[n],{meshes:e,primitives:n});if(c.length===1)return i.extensions&&fB(r,c[0],i),c[0];let l=new ZS;i.extensions&&fB(r,l,i),t.associations.set(l,{meshes:e});for(let e=0,t=c.length;e<t;e++)l.add(c[e]);return l})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn(`THREE.GLTFLoader: Missing camera parameters.`);return}return n.type===`perspective`?t=new GS(Xy.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type===`orthographic`&&(t=new ZD(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),pB(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let e=0,r=t.joints.length;e<r;e++)n.push(this._loadNodeShallow(t.joints[e]));return t.inverseBindMatrices===void 0?n.push(null):n.push(this.getDependency(`accessor`,t.inverseBindMatrices)),Promise.all(n).then(function(e){let n=e.pop(),r=e,i=[],a=[];for(let e=0,o=r.length;e<o;e++){let o=r[e];if(o){i.push(o);let t=new Xb;n!==null&&t.fromArray(n.array,e*16),a.push(t)}else console.warn(`THREE.GLTFLoader: Joint "%s" could not be found.`,t.joints[e])}return new zC(i,a)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],i=r.name?r.name:`animation_`+e,a=[],o=[],s=[],c=[],l=[];for(let e=0,t=r.channels.length;e<t;e++){let t=r.channels[e],n=r.samplers[t.sampler],i=t.target,u=i.node,d=r.parameters===void 0?n.input:r.parameters[n.input],f=r.parameters===void 0?n.output:r.parameters[n.output];i.node!==void 0&&(a.push(this.getDependency(`node`,u)),o.push(this.getDependency(`accessor`,d)),s.push(this.getDependency(`accessor`,f)),c.push(n),l.push(i))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(s),Promise.all(c),Promise.all(l)]).then(function(e){let t=e[0],a=e[1],o=e[2],s=e[3],c=e[4],l=[];for(let e=0,r=t.length;e<r;e++){let r=t[e],i=a[e],u=o[e],d=s[e],f=c[e];if(r===void 0)continue;r.updateMatrix&&r.updateMatrix();let p=n._createAnimationTracks(r,i,u,d,f);if(p)for(let e=0;e<p.length;e++)l.push(p[e])}let u=new xD(i,void 0,l);return pB(u,r),u})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency(`mesh`,r.mesh).then(function(e){let t=n._getNodeRef(n.meshCache,r.mesh,e);return r.weights!==void 0&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]}),t})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],i=n._loadNodeShallow(e),a=[],o=r.children||[];for(let e=0,t=o.length;e<t;e++)a.push(n.getDependency(`node`,o[e]));let s=r.skin===void 0?Promise.resolve(null):n.getDependency(`skin`,r.skin);return Promise.all([i,Promise.all(a),s]).then(function(e){let t=e[0],n=e[1],r=e[2];r!==null&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(r,bB)});for(let e=0,r=n.length;e<r;e++)t.add(n[e]);return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new FC:t.length>1?new ZS:t.length===1?t[0]:new Cx,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(i.name&&(o.userData.name=i.name,o.name=a),pB(o,i),i.extensions&&fB(n,o,i),i.matrix!==void 0){let e=new Xb;e.fromArray(i.matrix),o.applyMatrix4(e)}else i.translation!==void 0&&o.position.fromArray(i.translation),i.rotation!==void 0&&o.quaternion.fromArray(i.rotation),i.scale!==void 0&&o.scale.fromArray(i.scale);if(!r.associations.has(o))r.associations.set(o,{});else if(i.mesh!==void 0&&r.meshCache.refs[i.mesh]>1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new ZS;n.name&&(i.name=r.createUniqueName(n.name)),pB(i,n),n.extensions&&fB(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e<t;e++)o.push(r.getDependency(`node`,a[e]));return Promise.all(o).then(function(e){for(let t=0,n=e.length;t<n;t++)i.add(e[t]);return r.associations=(e=>{let t=new Map;for(let[e,n]of r.associations)(e instanceof Wx||e instanceof hb)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];cB[i.path]===cB.weights?e.traverse(function(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}):s.push(o);let c;switch(cB[i.path]){case cB.weights:c=gD;break;case cB.rotation:c=vD;break;case cB.translation:case cB.scale:c=bD;break;default:switch(n.itemSize){case 1:c=gD;break;default:c=bD;break}break}let l=r.interpolation===void 0?Ev:lB[r.interpolation],u=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e<n;e++){let n=new c(s[e]+`.`+cB[i.path],t.array,u,l);r.interpolation===`CUBICSPLINE`&&this._createCubicSplineTrackInterpolant(n),a.push(n)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let e=vB(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof vD?tB:$z)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function SB(e,t,n){let r=t.attributes,i=new Cb;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new Y(t[0],t[1],t[2]),new Y(a[0],a[1],a[2])),e.normalized){let t=vB(rB[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new Y,t=new Y;for(let r=0,i=a.length;r<i;r++){let i=a[r];if(i.POSITION!==void 0){let r=n.json.accessors[i.POSITION],a=r.min,o=r.max;if(a!==void 0&&o!==void 0){if(t.setX(Math.max(Math.abs(a[0]),Math.abs(o[0]))),t.setY(Math.max(Math.abs(a[1]),Math.abs(o[1]))),t.setZ(Math.max(Math.abs(a[2]),Math.abs(o[2]))),r.normalized){let e=vB(rB[r.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`)}}i.expandByVector(e)}e.boundingBox=i;let o=new Vb;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,e.boundingSphere=o}function CB(e,t,n){let r=t.attributes,i=[];function a(t,r){return n.getDependency(`accessor`,t).then(function(t){e.setAttribute(r,t)})}for(let t in r){let n=sB[t]||t.toLowerCase();n in e.attributes||i.push(a(r[t],n))}if(t.indices!==void 0&&!e.index){let r=n.getDependency(`accessor`,t.indices).then(function(t){e.setIndex(t)});i.push(r)}return ab.workingColorSpace!==`srgb-linear`&&`COLOR_0`in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ab.workingColorSpace}" not supported.`),pB(e,t),SB(e,t,n),Promise.all(i).then(function(){return t.targets===void 0?e:mB(e,t.targets,n)})}async function wB(e,t){let n=(await new Tz().parseAsync(e,``)).scene;return n.traverse(e=>{e.visible=!1}),t.add(n),n}function TB(e,t){t.remove(e),e.traverse(e=>{let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(e=>e.dispose()):t.material?.dispose()})}var EB=class{constructor(e){this.onPointer=e=>{e.type===`pointerdown`?(this.start(e.clientX,e.clientY),this.mouseDown=!0):e.type===`pointermove`&&this.mouseDown?this.move(e.clientX,e.clientY):e.type===`pointerup`&&this.end()},this.scene=e.scene,this.renderer=e.renderer,this.camera=e.camera,this.container=e.container,this.controls=e.controls,this.draggableBodyIds=e.draggableBodyIds??null,this.mousePos=new J,this.raycaster=new ok,this.raycaster.params.Line.threshold=.1,this.grabDistance=0,this.active=!1,this.mouseDown=!1,this.physicsObject=null,this.localHit=new Y,this.worldHit=new Y,this.currentWorld=new Y,this.offset=new Y,this.arrow=new ZS;let t=new rT(.008,.008,1),n=new GE({color:16737095,transparent:!0,opacity:.5,metalness:0,roughness:.2});this.arrowShaft=new kS(t,n),this.arrowShaft.position.y=.5;let r=new iT(.03,.1);this.arrowHead=new kS(r,n),this.arrowHead.position.y=1,this.arrow.add(this.arrowShaft),this.arrow.add(this.arrowHead),this.arrow.visible=!1,this.scene.add(this.arrow),this.container.addEventListener(`pointerdown`,this.onPointer,!0),document.addEventListener(`pointermove`,this.onPointer,!0),document.addEventListener(`pointerup`,this.onPointer,!0)}updateRaycaster(e,t){let n=this.renderer.domElement.getBoundingClientRect();this.mousePos.x=(e-n.left)/n.width*2-1,this.mousePos.y=-((t-n.top)/n.height)*2+1,this.raycaster.setFromCamera(this.mousePos,this.camera)}start(e,t){this.physicsObject=null,this.updateRaycaster(e,t);let n=this.raycaster.intersectObjects(this.scene.children,!0);for(let e of n){let t=e.object;if(!this.shouldIgnoreForDrag(t)&&this.isDraggableObject(t)){this.physicsObject=t,this.grabDistance=e.distance;let n=this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance);this.localHit.copy(t.worldToLocal(n.clone())),this.worldHit.copy(n),this.currentWorld.copy(n),this.offset.set(0,0,0),this.arrow.position.copy(n),this.arrow.visible=!1,this.active=!0,this.controls.enabled=!1;break}}}setDraggableBodyIds(e){this.draggableBodyIds=e}isDraggableObject(e){if(!(`bodyID`in e)||typeof e.bodyID!=`number`)return!1;let t=e.bodyID;return!(t<=0||this.draggableBodyIds&&!this.draggableBodyIds.has(t))}shouldIgnoreForDrag(e){let t=e;for(;t;){if(t.userData?.ignoreDragForce===!0)return!0;t=t.parent}return!1}move(e,t){this.active&&this.updateRaycaster(e,t)}update(){if(!this.physicsObject||!this.active)return;this.raycaster.setFromCamera(this.mousePos,this.camera),this.currentWorld.copy(this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance)),this.worldHit.copy(this.localHit),this.physicsObject.localToWorld(this.worldHit),this.offset.copy(this.currentWorld).sub(this.worldHit),this.arrow.position.copy(this.worldHit);let e=this.offset.length();if(e>.001){this.arrow.visible=!0;let t=this.offset.clone().normalize();this.arrow.quaternion.setFromUnitVectors(new Y(0,1,0),t);let n=.1,r=Math.max(.01,e-n);this.arrowShaft.scale.y=r,this.arrowShaft.position.y=r/2,this.arrowHead.position.y=r+n/2}else this.arrow.visible=!1}end(){this.physicsObject=null,this.active=!1,this.controls.enabled=!0,this.arrow.visible=!1,this.mouseDown=!1}dispose(){this.container.removeEventListener(`pointerdown`,this.onPointer,!0),document.removeEventListener(`pointermove`,this.onPointer,!0),document.removeEventListener(`pointerup`,this.onPointer,!0),this.arrow.parent&&this.scene.remove(this.arrow),this.arrowShaft.geometry.dispose(),this.arrowHead.geometry.dispose(),this.arrowShaft.material&&this.arrowShaft.material.dispose()}},DB={lookat:[0,0,0],distance:4,elevation:-30,azimuth:45,fovy:45,originType:`AUTO`,enableReflections:!0,enableShadows:!0,height:240,width:320};function OB(e,t,n,r){let i=n*Math.PI/180,a=r*Math.PI/180;return BN([e[0]+t*Math.cos(i)*Math.cos(a),e[1]+t*Math.cos(i)*Math.sin(a),e[2]-t*Math.sin(i)])}function kB(e,t,n,r,i){let a={trackBodyId:null,prevBodyPos:null};n.enabled=!0;let o=e?.lookat??DB.lookat,s=e?.distance??DB.distance,c=e?.elevation??DB.elevation,l=e?.azimuth??DB.azimuth;if(t.fov=e?.fovy??DB.fovy,t.updateProjectionMatrix(),t.position.copy(OB(o,s,c,l)),n.target.copy(BN(o)),n.update(),!e)return a;let u=e.originType??`AUTO`;if(u===`ASSET_BODY`&&e.bodyName&&r){let t=e.bodyName,n=e.entityName,i=n?`${n}/${t}`:null;for(let e=0;e<r.nbody;e++){let n=r.body(e).name;if(n===t||n===i||n.endsWith(`/${t}`)){a.trackBodyId=e;break}}a.trackBodyId===null&&console.warn(`[Camera] bodyName: body "${e.bodyName}" not found.`)}else (u===`AUTO`||u===`ASSET_ROOT`)&&r&&r.nbody>1&&(a.trackBodyId=1);if(a.trackBodyId!==null&&i){let e=BN(i.xpos.slice(a.trackBodyId*3,a.trackBodyId*3+3));t.position.add(e),n.target.add(e),a.prevBodyPos=e,n.update()}return a}function AB(e,t,n,r){if(r.trackBodyId!==null){let i=r.trackBodyId,a=BN(e.xpos.slice(i*3,i*3+3));if(r.prevBodyPos!==null){let e=a.clone().sub(r.prevBodyPos);t.position.add(e),n.target.add(e)}r.prevBodyPos=a}}var jB={},MB=class{constructor(e,t){this.runner=e,this.config=t}},NB={};async function PB(e){let t=new DecompressionStream(`deflate-raw`),n=t.writable.getWriter(),r=t.readable.getReader();n.write(e),n.close();let i=[],a=0;for(;;){let{done:e,value:t}=await r.read();if(e)break;i.push(t),a+=t.byteLength}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function FB(e){let t=[147,78,85,77,80,89];for(let n=0;n<t.length;n++)if(e[n]!==t[n])throw Error(`Invalid .npy magic number`);let n=e[6],r,i;n===1?(r=e[8]|e[9]<<8,i=10):(r=e[8]|e[9]<<8|e[10]<<16|e[11]<<24,i=12);let a=e.slice(i,i+r),o=new TextDecoder().decode(a),s=o.match(/'descr'\s*:\s*'([^']+)'/),c=o.match(/'shape'\s*:\s*\(([^)]*)\)/),l=o.match(/'fortran_order'\s*:\s*(True|False)/);if(!s||!c)throw Error(`Cannot parse .npy header: ${o}`);let u=s[1];if(l&&l[1]===`True`)throw Error(`Fortran-ordered arrays not supported`);let d=c[1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>parseInt(e,10)),f=i+r,p=e.slice(f),m=u[0],h=u.slice(1),g=m===`>`||m===`=`&&!LB(),_;if(h===`f4`)_=new Float32Array(p.buffer,p.byteOffset,p.byteLength/4),g&&(_=RB(_));else if(h===`f8`){let e=new Float64Array(p.buffer,p.byteOffset,p.byteLength/8);g&&(e=zB(e)),_=new Float32Array(e.length);for(let t=0;t<e.length;t++)_[t]=e[t]}else if(h===`i4`){let e=new Int32Array(p.buffer,p.byteOffset,p.byteLength/4);g&&(e=BB(e)),_=new Float32Array(e.length);for(let t=0;t<e.length;t++)_[t]=e[t]}else if(h===`i8`){let e=new BigInt64Array(p.buffer,p.byteOffset,p.byteLength/8);g&&(e=VB(e)),_=new Float32Array(e.length);for(let t=0;t<e.length;t++)_[t]=Number(e[t])}else{let e=u.match(/^S(\d+)$/);if(e){let t=parseInt(e[1],10),n=p.length/t,r=d.reduce((e,t)=>e*t,1);if(n!==r)throw Error(`npz: byte-string array size mismatch (shape ${d} expects ${r} elements, got ${n})`);let i=new TextDecoder(`utf-8`),a=[];for(let e=0;e<n;e++){let n=p.slice(e*t,(e+1)*t),r=n.indexOf(0);a.push(i.decode(r>=0?n.slice(0,r):n))}return{shape:d,data:new Float32Array,strings:a}}let t=h.match(/^U(\d+)$/);if(t){let e=parseInt(t[1],10),n=e*4,r=p.length/n,i=d.reduce((e,t)=>e*t,1);if(r!==i)throw Error(`npz: unicode array size mismatch (shape ${d} expects ${i} elements, got ${r})`);let a=new DataView(p.buffer,p.byteOffset,p.byteLength),o=!g,s=[];for(let t=0;t<r;t++){let r=[];for(let i=0;i<e;i++){let e=a.getUint32(t*n+i*4,o);if(e===0)break;r.push(e)}s.push(String.fromCodePoint(...r))}return{shape:d,data:new Float32Array,strings:s}}throw Error(h===`O`?IB:`Unsupported numpy dtype: ${u}`)}return{shape:d,data:_}}var IB=`npz: pickled python objects (|O dtype) cannot be loaded in the browser`;function LB(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,1,!0),new Int16Array(e)[0]===1}function RB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getFloat32(r*4,!0);return n}function zB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float64Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getFloat64(r*8,!0);return n}function BB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Int32Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getInt32(r*4,!0);return n}function VB(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new BigInt64Array(e.length);for(let r=0;r<e.length;r++)n[r]=t.getBigInt64(r*8,!0);return n}async function HB(e){let t=new Uint8Array(e),n={},r=0;for(;r+30<=t.length&&!(t[r]!==80||t[r+1]!==75||t[r+2]!==3||t[r+3]!==4);){let e=t[r+8]|t[r+9]<<8,i=(t[r+22]|t[r+23]<<8|t[r+24]<<16|t[r+25]<<24)>>>0,a=(t[r+18]|t[r+19]<<8|t[r+20]<<16|t[r+21]<<24)>>>0,o=t[r+26]|t[r+27]<<8,s=t[r+28]|t[r+29]<<8,c=t.slice(r+30,r+30+o),l=new TextDecoder().decode(c);if(a===4294967295||i===4294967295){let e=r+30+o,n=e;for(;n+4<=e+s;){let e=t[n]|t[n+1]<<8,r=t[n+2]|t[n+3]<<8;if(e===1){let e=n+4;if(i===4294967295&&e+8<=n+4+r&&(e+=8),a===4294967295&&e+8<=n+4+r){let n=(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0;a=((t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0)*4294967296+n}break}n+=4+r}}let u=r+30+o+s,d=t.slice(u,u+a);if(r=u+a,l.endsWith(`/`))continue;l.endsWith(`.npy`)&&(l=l.slice(0,-4));let f;if(e===0)f=d;else if(e===8)f=await PB(d);else{console.warn(`[NPZ] Unsupported compression method ${e} for ${l}`);continue}try{n[l]=FB(f)}catch(e){(e instanceof Error?e.message:String(e))===IB?console.debug(`[NPZ] Skipping pickled object field "${l}"`):console.warn(`[NPZ] Failed to parse ${l}:`,e)}}return n}function UB(e){return typeof e==`function`?e():Promise.resolve(e)}function WB(e){let t=Math.hypot(e[0]??1,e[1]??0,e[2]??0,e[3]??0)||1;return new Float32Array([(e[0]??1)/t,(e[1]??0)/t,(e[2]??0)/t,(e[3]??0)/t])}function GB(e){let t=e.shape[0]??0,n=e.shape.length<=1?1:e.shape.slice(1).reduce((e,t)=>e*t,1),r=[];for(let i=0;i<t;i++){let t=new Float32Array(n),a=i*n;for(let r=0;r<n;r++)t[r]=e.data[a+r]??0;r.push(t)}return r}function KB(e,t){if(!Array.isArray(e)||e.length<2)return t;let n=Number(e[0]),r=Number(e[1]);return!Number.isFinite(n)||!Number.isFinite(r)?t:[n,r]}function qB(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let n of[`x`,`y`,`z`,`roll`,`pitch`,`yaw`]){let r=KB(e[n],[0,0]);(r[0]!==0||r[1]!==0)&&(t[n]=r)}return t}function JB(e){return e?e[0]+Math.random()*(e[1]-e[0]):0}function YB(e,t){let n=e[0]??1,r=e[1]??0,i=e[2]??0,a=e[3]??0,o=t[0]??1,s=t[1]??0,c=t[2]??0,l=t[3]??0;return new Float32Array([n*o-r*s-i*c-a*l,n*s+r*o+i*l-a*c,n*c-r*l+i*o+a*s,n*l+r*c-i*s+a*o])}function XB(e,t,n){let r=Math.cos(e*.5),i=Math.sin(e*.5),a=Math.cos(t*.5),o=Math.sin(t*.5),s=Math.cos(n*.5),c=Math.sin(n*.5);return new Float32Array([r*a*s+i*o*c,i*a*s-r*o*c,r*o*s+i*a*c,r*a*c-i*o*s])}function ZB(e){let t=e.clone();return`transparent`in t&&(t.transparent=!0),`opacity`in t&&(t.opacity=.5),`depthWrite`in t&&(t.depthWrite=!1),`color`in t&&t.color instanceof X&&(t.color=new X(.5,.7,.5)),t}function QB(e){let t=!1;return e.traverse(e=>{e instanceof kS&&(t=!0)}),t}var $B=class{constructor(e,t,n){this.context=n,this.motions=Array.isArray(t.motions)?t.motions:[],this.loadedMotions=new Map,this.sampleHz=50,this.selectedMotionName=this.motions.find(e=>e.default)?.name??this.motions[0]?.name??null,this.selectedMotion=null,this.selectedAnchorBodyIndex=0,this.selectedRootBodyIndex=0,this.datasetQposAdr=[],this.frameAccumulator=0,this.justReset=!0,this.referenceVisible=!0,this.samplingMode=typeof t.sampling_mode==`string`?t.sampling_mode:`start`,this.poseRange=qB(t.pose_range),this.velocityRange=qB(t.velocity_range),this.jointPositionRange=KB(t.joint_position_range,[0,0]),this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.nJoints=this.motions.find(e=>e.name===this.selectedMotionName)?.dataset_joint_names?.length??0,this.ghostBodies=new Map,this.ghostData=n.mjModel?new n.mujoco.MjData(n.mjModel):null,this.ghostRoot=this.createGhostRoot(),this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[]}getCommand(){if(!this.selectedMotion||this.refLen===0)return new Float32Array(this.nJoints*2);if(this.selectedMotion.clip_format===`qpos`)return new Float32Array;let e=this.refJointPos[this.refIdx]??new Float32Array(this.nJoints),t=this.selectedMotion.jointVel[this.refIdx]??new Float32Array(this.nJoints),n=new Float32Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}getUiConfig(){return null}async setSelectedMotion(e){if(e===null)return this.selectedMotionName=null,this.selectedMotion=null,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[],this.refLen=0,this.nJoints=0,this.updateGhostPose(),!1;let t=this.motions.find(t=>t.name===e);if(!t)return!1;let n=this.loadedMotions.get(e)??await this.loadMotion(t);return this.loadedMotions.set(e,n),this.selectedMotionName=e,this.selectedMotion=n,this.selectedAnchorBodyIndex=Math.max(0,n.body_names.indexOf(n.anchor_body_name)),this.selectedRootBodyIndex=0,this.datasetQposAdr=this.resolveQposAdr(n.dataset_joint_names??[]),this.refLen=n.frameCount,this.refJointPos=n.jointPos,this.refIdx=this.sampleInitialFrame(this.refLen),this.nJoints=n.jointPos[0]?.length??0,this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose(),!0}setReferenceVisible(e){this.referenceVisible=e,this.ghostRoot&&(this.ghostRoot.visible=e&&this.selectedMotion!==null)}reset(){this.refIdx=this.sampleInitialFrame(this.refLen),this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose()}update(e){if(!this.selectedMotion||this.refLen<=1)return;if(this.justReset){this.justReset=!1,this.updateGhostPose();return}if(this.selectedMotion.time_source===`sim`){let e=this.context.mjData?.time??0;this.refIdx=this.sampleHz>0?Math.floor(e*this.sampleHz)%this.refLen:0,this.updateGhostPose();return}let t=this.selectedMotion?.loop!==!1;this.frameAccumulator+=e*this.sampleHz;let n=!1;for(;this.frameAccumulator>=1;){if(this.refIdx+=1,this.refIdx>=this.refLen){if(!t){this.refIdx=this.refLen-1,this.frameAccumulator=0;break}this.refIdx=0,n=!0}--this.frameAccumulator}n&&this.context.requestReset?.(),this.updateGhostPose()}updateDebugVisuals(){this.ghostRoot&&(this.ghostRoot.visible=this.referenceVisible&&this.selectedMotion!==null)}dispose(){this.ghostRoot&&(this.ghostRoot.parent?.remove(this.ghostRoot),this.ghostRoot.traverse(e=>{if(e instanceof kS)if(Array.isArray(e.material))for(let t of e.material)t.dispose?.();else e.material?.dispose?.()})),this.ghostData?.delete?.()}isReady(){return this.selectedMotion!==null&&this.refLen>0}getSelectedMotion(){return this.selectedMotion}getSelectedMotionName(){return this.selectedMotionName}getAnchorBodyName(){return this.selectedMotion?.anchor_body_name??this.motions.find(e=>e.name===this.selectedMotionName)?.anchor_body_name??null}getBodyNames(){return this.selectedMotion?.body_names??this.motions.find(e=>e.name===this.selectedMotionName)?.body_names??[]}getAnchorBodyIndex(){return this.selectedAnchorBodyIndex}getAnchorPos(e=this.refIdx){if(!this.selectedMotion)return null;let t=this.refBodyPosW[e];if(!t)return null;let n=this.selectedAnchorBodyIndex*3;return t.slice(n,n+3)}getAnchorQuat(e=this.refIdx){if(!this.selectedMotion)return null;let t=this.refBodyQuatW[e];if(!t)return null;let n=this.selectedAnchorBodyIndex*4;return WB(t.slice(n,n+4))}getBodyPosW(e=this.refIdx){if(!this.selectedMotion)return null;let t=this.refBodyPosW[e];return t?t.slice():null}createGhostRoot(){let e=this.context.bodies??null,t=this.context.mjModel;if(!e||!t)return null;let n=new ZS;n.name=`Tracking Ghost`,n.visible=!1;for(let[t,r]of Object.entries(e)){let e=Number(t);if(!this.isDynamicBody(e))continue;let i=r.clone(!0);i.traverse(e=>{e instanceof kS&&(Array.isArray(e.material)?e.material=e.material.map(ZB):e.material=ZB(e.material),e.renderOrder=2)}),QB(i)&&(this.ghostBodies.set(e,i),n.add(i))}return(this.context.mujocoRoot??this.context.scene).add(n),n}isDynamicBody(e){let t=this.context.mjModel;if(!t||e<=0||e>=t.nbody)return!1;let n=e;for(;n>0;){if(t.body_jntnum[n]>0)return!0;n=t.body_parentid[n]}return!1}async loadMotion(e){this.sampleHz=e.fps;let t=await HB(await UB(e.data)),n=[];if(e.clip_format===`qpos`){if(!t.qpos)throw Error(`Motion asset with clip_format='qpos' is missing 'qpos'`);let r=GB(t.qpos);return{...e,jointPos:n,jointVel:n,bodyPosW:n,bodyQuatW:n,bodyLinVelW:n,bodyAngVelW:n,qposFrames:r,frameCount:r.length}}for(let e of[`joint_pos`,`joint_vel`,`body_pos_w`,`body_quat_w`,`body_lin_vel_w`,`body_ang_vel_w`])if(!t[e])throw Error(`Motion asset is missing '${e}'`);let r=GB(t.joint_pos),i=GB(t.joint_vel),a=t.body_names?.strings??null,o=this.selectMotionBodyFrames(GB(t.body_pos_w),e.body_names,3,a),s=this.selectMotionBodyFrames(GB(t.body_quat_w),e.body_names,4,a),c=this.selectMotionBodyFrames(GB(t.body_lin_vel_w),e.body_names,3,a),l=this.selectMotionBodyFrames(GB(t.body_ang_vel_w),e.body_names,3,a);return{...e,jointPos:r,jointVel:i,bodyPosW:o,bodyQuatW:s,bodyLinVelW:c,bodyAngVelW:l,frameCount:r.length}}selectMotionBodyFrames(e,t,n,r=null){let i=this.context.mjModel,a=e[0];if(!i||!a||t.length===0)return e;let o=Math.floor(a.length/n);if(o===t.length)return e;let s;if(r!==null)s=t.map(e=>r.indexOf(e));else{let e=this.findBodyIdByName(t[0]);s=t.map(e=>this.findBodyIdByName(e)).map(t=>t-e)}return s.some(e=>e<0||e>=o)?(console.warn(`[TrackingCommand] Could not map all motion body names to source body indices; using raw body frames.`),e):e.map(e=>{let r=new Float32Array(t.length*n);for(let t=0;t<s.length;t++){let i=s[t]*n,a=t*n;for(let t=0;t<n;t++)r[a+t]=e[i+t]??0}return r})}updateReferenceState(){let e=this.selectedMotion;if(!e||e.frameCount===0||e.clip_format===`qpos`){this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[];return}this.refBodyPosW=e.bodyPosW.map(e=>e.slice()),this.refBodyQuatW=e.bodyQuatW.map(e=>e.slice()),this.refBodyLinVelW=e.bodyLinVelW.map(e=>e.slice()),this.refBodyAngVelW=e.bodyAngVelW.map(e=>e.slice()),this.refRootPos=this.refBodyPosW.map(e=>e.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3)),this.refRootQuat=this.refBodyQuatW.map(e=>WB(e.slice(this.selectedRootBodyIndex*4,this.selectedRootBodyIndex*4+4)))}applyReferenceStateToSim(){let e=this.context.mjModel,t=this.context.mjData,n=this.selectedMotion;if(!e||!t||!n||this.refLen===0||n.clip_format===`qpos`)return;let r=this.sampleRootPos(this.refIdx),i=this.sampleRootQuat(this.refIdx),a=this.findFreeJointIndex();if(r&&i&&a>=0){let n=e.jnt_qposadr[a],o=e.jnt_dofadr[a];t.qpos[n+0]=r[0]??0,t.qpos[n+1]=r[1]??0,t.qpos[n+2]=r[2]??0,t.qpos[n+3]=i[0]??1,t.qpos[n+4]=i[1]??0,t.qpos[n+5]=i[2]??0,t.qpos[n+6]=i[3]??0;let s=this.sampleRootVelocity(this.refIdx,this.refBodyLinVelW),c=this.sampleRootAngularVelocity(this.refIdx);s&&c&&(t.qvel[o+0]=s[0]??0,t.qvel[o+1]=s[1]??0,t.qvel[o+2]=s[2]??0,t.qvel[o+3]=c[0]??0,t.qvel[o+4]=c[1]??0,t.qvel[o+5]=c[2]??0)}let o=this.sampleJointPos(this.refIdx),s=n.jointVel[this.refIdx]??new Float32Array;for(let e=0;e<this.datasetQposAdr.length&&e<o.length;e++)t.qpos[this.datasetQposAdr[e]]=o[e]??0;for(let e=0;e<this.datasetQposAdr.length&&e<s.length;e++){let n=this.resolveQvelAdrForQposAdr(this.datasetQposAdr[e]);n>=0&&(t.qvel[n]=s[e]??0)}this.context.mujoco.mj_forward(e,t)}sampleRootPos(e){let t=this.refRootPos[e];if(!t)return null;let n=t.slice();return n[0]+=JB(this.poseRange.x),n[1]+=JB(this.poseRange.y),n[2]+=JB(this.poseRange.z),n}sampleRootQuat(e){let t=this.refRootQuat[e];if(!t)return null;let n=JB(this.poseRange.roll),r=JB(this.poseRange.pitch),i=JB(this.poseRange.yaw);return n===0&&r===0&&i===0?t:WB(YB(XB(n,r,i),t))}sampleRootVelocity(e,t){let n=t[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return n?(n[0]+=JB(this.velocityRange.x),n[1]+=JB(this.velocityRange.y),n[2]+=JB(this.velocityRange.z),n):null}sampleRootAngularVelocity(e){let t=this.refBodyAngVelW[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return t?(t[0]+=JB(this.velocityRange.roll),t[1]+=JB(this.velocityRange.pitch),t[2]+=JB(this.velocityRange.yaw),t):null}sampleInitialFrame(e){return e<=1||this.samplingMode===`start`?0:this.samplingMode===`uniform`?Math.floor(Math.random()*e):0}sampleJointPos(e){let t=this.refJointPos[e]??new Float32Array;if(this.jointPositionRange[0]===0&&this.jointPositionRange[1]===0)return t;let n=t.slice();for(let e=0;e<n.length;e++)n[e]+=JB(this.jointPositionRange);return n}resolveQposAdr(e){let t=this.context.mjModel;if(!t||e.length===0)return[];let n=[];for(let r of e){let e=-1;for(let n=0;n<t.njnt;n++){let i=t.jnt(n).name;if(i===r||i.endsWith(`/${r}`)){e=t.jnt_qposadr[n];break}}e>=0&&n.push(e)}return n}resolveQvelAdrForQposAdr(e){let t=this.context.mjModel;if(!t)return-1;for(let n=0;n<t.njnt;n++)if(t.jnt_qposadr[n]===e)return t.jnt_dofadr[n];return-1}findBodyIdByName(e){let t=this.context.mjModel;if(!t)return-1;for(let n=0;n<t.nbody;n++){let r=t.body(n).name;if(r===e||r.endsWith(`/${e}`))return n}return-1}updateGhostPose(){if(!this.ghostRoot||!this.ghostData||!this.context.mjModel||!this.selectedMotion||!this.refLen){this.ghostRoot&&(this.ghostRoot.visible=!1);return}if(this.selectedMotion.clip_format===`qpos`&&this.selectedMotion.qposFrames){let e=this.selectedMotion.qposFrames[this.refIdx];e&&this.ghostData.qpos.set(e),this.context.mujoco.mj_forward(this.context.mjModel,this.ghostData);for(let[e,t]of this.ghostBodies)aP(this.ghostData.xpos,e,t.position),oP(this.ghostData.xquat,e,t.quaternion);this.ghostRoot.visible=this.referenceVisible;return}let e=this.ghostData.qpos;e.set(this.context.mjModel.qpos0);let t=this.refRootPos[this.refIdx],n=this.refRootQuat[this.refIdx],r=this.findFreeJointIndex();if(r>=0&&t&&n){let i=this.context.mjModel.jnt_qposadr[r];e[i+0]=t[0]??0,e[i+1]=t[1]??0,e[i+2]=t[2]??0,e[i+3]=n[0]??1,e[i+4]=n[1]??0,e[i+5]=n[2]??0,e[i+6]=n[3]??0}let i=this.refJointPos[this.refIdx]??new Float32Array;for(let t=0;t<this.datasetQposAdr.length&&t<i.length;t++)e[this.datasetQposAdr[t]]=i[t]??0;this.context.mujoco.mj_forward(this.context.mjModel,this.ghostData);for(let[e,t]of this.ghostBodies)aP(this.ghostData.xpos,e,t.position),oP(this.ghostData.xquat,e,t.quaternion);this.ghostRoot.visible=this.referenceVisible}findFreeJointIndex(){let e=this.context.mjModel;if(!e)return-1;for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}};function eV(e,t){return`${e}:${t}`}function tV(e){return typeof e==`object`&&!!e&&`isReady`in e&&`getAnchorBodyName`in e&&`getBodyNames`in e}var nV={UiCommand:class{constructor(e,t){this.inputs=Array.isArray(t.ui?.inputs)?t.ui.inputs:[],this.values=new Map;for(let e of this.inputs)e.type===`slider`?this.values.set(e.name,e.default):e.type===`checkbox`&&this.values.set(e.name,+!!e.default)}getCommand(){let e=this.inputs.filter(e=>e.type===`slider`||e.type===`checkbox`),t=new Float32Array(e.length);for(let n=0;n<e.length;n++){let r=e[n],i=r.type===`checkbox`?+!!r.default:r.default;t[n]=this.values.get(r.name)??i??0}return t}getUiConfig(){return{inputs:this.inputs}}reset(){for(let e of this.inputs)e.type===`slider`?this.values.set(e.name,e.default):e.type===`checkbox`&&this.values.set(e.name,+!!e.default)}setValue(e,t){let n=this.inputs.find(t=>(t.type===`slider`||t.type===`checkbox`)&&t.name===e);if(!n)return 0;if(n.type===`checkbox`){let e=+(t>=.5);return this.values.set(n.name,e),e}let r=Math.max(n.min,Math.min(n.max,t));return this.values.set(n.name,r),r}},TrackingCommand:$B},rV=class{constructor(){this.terms=new Map,this.commands=new Map,this.commandGroups=new Map,this.values=new Map,this.listeners=new Set,this.context=null}initialize(e,t,n){this.clear(),this.context=t;let r={...nV,...NB,...n};for(let[n,i]of Object.entries(e)){let e=r[i.name];if(!e)throw Error(`Unknown command term: ${i.name}`);let a=new e(n,i,t);this.terms.set(n,a),this.registerUi(n,a)}}update(e){for(let t of this.terms.values())t.update?.(e)}updateDebugVisuals(){for(let e of this.terms.values())e.updateDebugVisuals?.()}resetTerms(){for(let e of this.terms.values())e.reset?.();this.syncValuesFromTerms(),this.emit({type:`reset`,commandId:`*`})}getCommandGroups(){return Array.from(this.commandGroups.keys())}getCommandsInGroup(e){return(this.commandGroups.get(e)??[]).map(e=>this.commands.get(e)).filter(Boolean)}getCommands(){return Array.from(this.commands.values())}getCommandById(e){return this.commands.get(e)}getValue(e){return this.values.get(e)??0}getValues(){let e={};for(let[t,n]of this.values)e[t]=n;return e}getCommand(e){let t=this.terms.get(e);return t?t.getCommand():new Float32Array}getTerm(e){return this.terms.get(e)}getContext(){return this.context}getVelocityCommand(){return this.terms.has(`velocity`)?this.getCommand(`velocity`):this.terms.has(`twist`)?this.getCommand(`twist`):new Float32Array([.5,0,0])}setValue(e,t){let n=this.commands.get(e);if(!n||n.config.type!==`slider`&&n.config.type!==`checkbox`)return;let r=this.terms.get(n.groupName),i=n.config.name,a=r?.setValue?r.setValue(i,t):void 0,o=typeof a==`number`?a:t;this.values.set(e,o),this.emit({type:`change`,commandId:e,groupName:n.groupName,value:o})}triggerButton(e){let t=this.commands.get(e);!t||t.config.type!==`button`||(this.terms.get(t.groupName)?.triggerButton?.(t.config.name),this.emit({type:`button`,commandId:e,groupName:t.groupName}))}resetToDefaults(){this.resetTerms()}addEventListener(e){this.listeners.add(e)}removeEventListener(e){this.listeners.delete(e)}clear(){for(let e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.context=null,this.emit({type:`clear`,commandId:``})}hasCommands(){return this.commands.size>0}dispose(){for(let e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.listeners.clear(),this.context=null}registerUi(e,t){let n=t.getUiConfig?.(),r=Array.isArray(n?.inputs)?n.inputs:[];if(r.length!==0){this.commandGroups.set(e,[]);for(let n of r){let i=eV(e,n.name);if(this.commands.set(i,{id:i,groupName:e,config:n}),this.commandGroups.get(e).push(i),n.type===`slider`||n.type===`checkbox`){let e=t.getCommand(),a=r.filter(e=>e.type===`slider`||e.type===`checkbox`).findIndex(e=>e.name===n.name),o=n.type===`checkbox`?+!!n.default:n.default;this.values.set(i,e[a]??o)}}this.emit({type:`group_registered`,commandId:e,groupName:e})}}syncValuesFromTerms(){for(let[e,t]of this.commands){if(t.config.type!==`slider`&&t.config.type!==`checkbox`)continue;let n=this.terms.get(t.groupName);if(!n)continue;let r=(n.getUiConfig?.()?.inputs??[]).filter(e=>e.type===`slider`||e.type===`checkbox`).findIndex(e=>e.name===t.config.name);if(r>=0){let t=n.getCommand();this.values.set(e,t[r]??this.values.get(e)??0)}}}emit(e){for(let t of this.listeners)try{t(e)}catch(e){console.warn(`[CommandManager] Listener error:`,e)}}};function iV(e){let t=e[0]??1,n=e[1]??0,r=e[2]??0,i=e[3]??0,a=Math.hypot(t,n,r,i);if(a<1e-9)return[1,0,0,0];let o=1/a;return[t*o,n*o,r*o,i*o]}function aV(e,t){let n=e[0]??1,r=e[1]??0,i=e[2]??0,a=e[3]??0,o=t[0]??1,s=t[1]??0,c=t[2]??0,l=t[3]??0;return[n*o-r*s-i*c-a*l,n*s+r*o+i*l-a*c,n*c-r*l+i*o+a*s,n*l+r*c-i*s+a*o]}function oV(e){let t=e[0]??1,n=e[1]??0,r=e[2]??0,i=e[3]??0,a=t*t+n*n+r*r+i*i;if(a<1e-9)return[1,0,0,0];let o=1/a;return[t*o,-n*o,-r*o,-i*o]}function sV(e,t){let n=e[0]??1,r=e[1]??0,i=e[2]??0,a=e[3]??0,o=t[0]??0,s=t[1]??0,c=t[2]??0,l=2*(i*c-a*s),u=2*(a*o-r*c),d=2*(r*s-i*o),f=i*d-a*u,p=a*l-r*d,m=r*u-i*l;return[o-n*l+f,s-n*u+p,c-n*d+m]}function cV(e){let[t,n,r,i]=iV(e),a=n*n,o=r*r,s=i*i,c=n*r,l=n*i,u=r*i,d=t*n,f=t*r,p=t*i;return[1-2*(o+s),2*(c-p),2*(c+p),1-2*(a+s),2*(l-f),2*(u+d)]}function lV(e,t=0){return typeof e==`number`?e:e instanceof Float32Array?e[t]??0:typeof e==`boolean`?+!!e:0}function uV(e){return e instanceof Float32Array?e:typeof e==`number`?new Float32Array([e]):new Float32Array}function dV(e,t){let n=e.getContext()?.mjModel??null;if(!n)return-1;for(let e=0;e<n.nbody;e++){let r=n.body(e).name;if(r===t||r.endsWith(`/${t}`))return e}return-1}function fV(e){let t=e.runner.getContext()?.commandManager?.getTerm(`motion`);return tV(t)&&t.isReady()?t:null}function pV(e){let t=e.runner.getContext()?.commandManager?.getTerm(`motion`);return typeof t==`object`&&t&&`refRootPos`in t&&`refRootQuat`in t&&`refJointPos`in t&&typeof t.isReady==`function`?t:null}function mV(e,t,n){let r=e+t;return r<0?0:r>=n?Math.max(0,n-1):r}function hV(e,t,n){let r=new Uint8Array(e.names),i=new TextDecoder,a=[];for(let e=0;e<t;e++){let t=n[e],o=t;for(;o<r.length&&r[o]!==0;)o++;a.push(i.decode(r.subarray(t,o)))}return a}function gV(e){return hV(e,e.njnt,e.name_jntadr)}function _V(e,t){let n=e.getContext()?.mjModel??null;if(!n)return t.map(()=>-1);let r=gV(n);return t.map(e=>{let t=r.indexOf(e);return t<0?-1:n.jnt_qposadr[t]})}function vV(e,t){let n=e.getContext()?.mjModel??null;if(!n)return t.map(()=>-1);let r=gV(n);return t.map(e=>{let t=r.indexOf(e);return t<0?-1:n.jnt_dofadr[t]})}function yV(e,t){let n=e.getContext()?.mjModel??null;return n?hV(n,n.nsite,n.name_siteadr).indexOf(t):-1}function bV(e,t){let n=e.getContext()?.mjModel??null;if(!n)return{adr:0,dim:0};let r=hV(n,n.nsensor,n.name_sensoradr).indexOf(t);return r<0?{adr:0,dim:0}:{adr:n.sensor_adr[r],dim:n.sensor_dim[r]}}function xV(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:null}var SV={Const:(e,t)=>Number(t.value??0),StepCount:(e,t,n,r)=>{let i=(r.count??0)+1;return r.count=i,i},Param:(e,t,n)=>{let r=n.params[String(t.name)];return typeof r==`number`?r:Array.isArray(r)?Float32Array.from(r):0},RootAngVelB:(e,t,n)=>n.state.rootAngVel?new Float32Array(n.state.rootAngVel):new Float32Array(3),RootLinkLinVelB:(e,t,n)=>n.state.rootLinVel?new Float32Array(n.state.rootLinVel):new Float32Array(3),RootLinkPosW:(e,t,n)=>n.state.rootPos?new Float32Array(n.state.rootPos):new Float32Array(3),RootLinkQuatW:(e,t,n)=>n.state.rootQuat?new Float32Array(n.state.rootQuat):new Float32Array([1,0,0,0]),ProjectedGravityB:(e,t,n)=>{let r=n.state.rootQuat??new Float32Array([1,0,0,0]),i=r[0],a=r[1],o=r[2],s=r[3],c=2*(o*-1-s*0),l=2*(s*0-a*-1),u=2*(a*0-o*0),d=o*u-s*l,f=s*c-a*u,p=a*l-o*c;return new Float32Array([0-i*c+d,0-i*l+f,-1-i*u+p])},Add:e=>TV(e[0],e[1],(e,t)=>e+t),Sub:e=>TV(e[0],e[1],(e,t)=>e-t),Mul:e=>TV(e[0],e[1],(e,t)=>e*t),Div:e=>TV(e[0],e[1],(e,t)=>e/t),Neg:e=>wV(e[0],e=>-e),Abs:e=>wV(e[0],Math.abs),Sqrt:e=>wV(e[0],Math.sqrt),Acos:e=>wV(e[0],e=>Math.acos(Math.max(-1,Math.min(1,e)))),Sum:e=>{let t=uV(e[0]),n=0;for(let e=0;e<t.length;e++)n+=t[e];return n},Index:(e,t)=>uV(e[0])[Number(t.i??0)]??0,Slice:(e,t)=>{let n=uV(e[0]),r=Number(t.start??0),i=Number(t.len??0),a=new Float32Array(i);for(let e=0;e<i;e++)a[e]=n[r+e]??0;return a},Gt:e=>EV(e[0],e[1],(e,t)=>e>t),Lt:e=>EV(e[0],e[1],(e,t)=>e<t),Ge:e=>EV(e[0],e[1],(e,t)=>e>=t),Le:e=>EV(e[0],e[1],(e,t)=>e<=t),Any:e=>DV(e[0],(e,t)=>e||t,!1),All:e=>DV(e[0],(e,t)=>e&&t,!0),Or:e=>CV(e[0],e[1],(e,t)=>e||t),And:e=>CV(e[0],e[1],(e,t)=>e&&t),Not:e=>{let t=e[0];if(typeof t==`boolean`)return!t;if(typeof t==`number`)return t===0;if(t instanceof Uint8Array){let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=+!t[n];return e}return!1},ConstVec:(e,t)=>{let n=Array.isArray(t.values)?t.values:[];return Float32Array.from(n)},SpawnCapture:(e,t,n,r)=>(r.captured===void 0&&(r.captured=uV(e[0]).slice()),r.captured),QuatApplyInv:e=>Float32Array.from(sV(uV(e[0]),uV(e[1]))),TrackingAnchorPos:(e,t,n)=>{let r=fV(n)?.getAnchorPos()??null;return r?new Float32Array(r):new Float32Array(3)},TrackingAnchorQuat:(e,t,n)=>{let r=fV(n)?.getAnchorQuat()??null;return r?new Float32Array(r):new Float32Array([1,0,0,0])},TrackingCurrentAnchorPos:(e,t,n)=>{let r=fV(n)?.getAnchorBodyName()??null,i=n.runner.getContext()?.mjData??null;if(!r||!i)return new Float32Array(3);let a=dV(n.runner,r);return a<0?new Float32Array(3):new Float32Array([i.xpos[a*3],i.xpos[a*3+1],i.xpos[a*3+2]])},TrackingCurrentAnchorQuat:(e,t,n)=>{let r=fV(n)?.getAnchorBodyName()??null,i=n.runner.getContext()?.mjData??null;if(!r||!i)return new Float32Array([1,0,0,0]);let a=dV(n.runner,r);return a<0?new Float32Array([1,0,0,0]):new Float32Array(i.xquat.slice(a*4,a*4+4))},TrackingBodyPosZDeviationMax:(e,t,n)=>{let r=fV(n),i=n.runner.getContext()?.mjData??null;if(!r||!i)return 0;let a=r.getBodyPosW();if(!a)return 0;let o=r.getBodyNames(),s=Array.isArray(t.body_names)&&t.body_names.length>0?t.body_names:o,c=0;for(let e of s){let t=o.indexOf(e),r=dV(n.runner,e);if(t<0||r<0)continue;let s=a[t*3+2]??0,l=i.xpos[r*3+2]??0,u=Math.abs(s-l);u>c&&(c=u)}return c},Clip:(e,t)=>{let n=Number(t.min??-1/0),r=Number(t.max??1/0);return wV(e[0],e=>Math.min(r,Math.max(n,e)))},History:(e,t,n,r)=>{let i=Math.max(1,Math.floor(Number(t.steps??1))),a=uV(e[0]),o=r.buffer;if(o===void 0||o.length!==i||o[0].length!==a.length)o=Array.from({length:i},()=>a.slice()),r.buffer=o;else{for(let e=o.length-1;e>0;e--)o[e].set(o[e-1]);o[0].set(a)}if(i===1)return new Float32Array(o[0]);let s=a.length,c=new Float32Array(s*i);if(t.interleaved)for(let e=0;e<s;e++)for(let t=0;t<i;t++)c[e*i+t]=o[t][e];else for(let e=0;e<i;e++)c.set(o[e],e*s);return c},Concat:e=>{let t=0,n=e.map(e=>uV(e));for(let e of n)t+=e.length;let r=new Float32Array(t),i=0;for(let e of n)r.set(e,i),i+=e.length;return r},Cos:e=>wV(e[0],Math.cos),Sin:e=>wV(e[0],Math.sin),QuatMul:e=>Float32Array.from(aV(uV(e[0]),uV(e[1]))),QuatInv:e=>Float32Array.from(oV(uV(e[0]))),QuatToRot6d:e=>Float32Array.from(cV(uV(e[0]))),JointPos:(e,t,n)=>{let r=xV(t.joint_names);if(r===null){let e=n.state.jointPos;return e?new Float32Array(e):new Float32Array(n.runner.getNumActions())}let i=_V(n.runner,r),a=n.runner.getContext()?.mjData?.qpos,o=new Float32Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]>=0&&a!==void 0?a[i[e]]:0;return o},DefaultJointPos:(e,t,n)=>{let r=xV(t.joint_names);if(r===null)return new Float32Array(n.runner.getDefaultJointPos());let i=_V(n.runner,r),a=n.runner.getContext()?.mjModel?.qpos0,o=new Float32Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]>=0&&a!==void 0?a[i[e]]:0;return o},JointVel:(e,t,n)=>{let r=xV(t.joint_names);if(r===null){let e=n.state.jointVel;return e?new Float32Array(e):new Float32Array(n.runner.getNumActions())}let i=vV(n.runner,r),a=n.runner.getContext()?.mjData?.qvel,o=new Float32Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]>=0&&a!==void 0?a[i[e]]:0;return o},PrevAction:(e,t,n)=>new Float32Array(n.runner.getLastActions()),CommandValue:(e,t,n)=>{let r=String(t.command??``),i=r?n.runner.getContext()?.commandManager?.getCommand(r):null;return i?new Float32Array(i):new Float32Array},Sensor:(e,t,n)=>{let{adr:r,dim:i}=bV(n.runner,String(t.sensor??``)),a=n.runner.getContext()?.mjData?.sensordata,o=new Float32Array(i);if(a!==void 0)for(let e=0;e<i;e++)o[e]=a[r+e]??0;return o},SitePos:(e,t,n)=>{let r=yV(n.runner,String(t.site??``)),i=n.runner.getContext()?.mjData?.site_xpos;return r<0||i===void 0?new Float32Array(3):new Float32Array([i[r*3],i[r*3+1],i[r*3+2]])},BodyPos:(e,t,n)=>{let r=dV(n.runner,String(t.body??``)),i=n.runner.getContext()?.mjData?.xpos;return r<0||i===void 0?new Float32Array(3):new Float32Array([i[r*3],i[r*3+1],i[r*3+2]])},BodyQuat:(e,t,n)=>{let r=dV(n.runner,String(t.body??``)),i=n.runner.getContext()?.mjData?.xquat;return r<0||i===void 0?new Float32Array([1,0,0,0]):new Float32Array(i.slice(r*4,r*4+4))},TrackingRefField:(e,t,n)=>{let r=String(t.field??``),i=()=>r===`root_quat`?new Float32Array([1,0,0,0]):r===`root_pos`?new Float32Array(3):new Float32Array(n.runner.getNumActions()),a=pV(n);if(!a||!a.isReady())return i();let o=(r===`root_pos`?a.refRootPos:r===`root_quat`?a.refRootQuat:a.refJointPos)[mV(a.refIdx,Number(t.step??0),a.refLen)];return o?new Float32Array(o):i()},TrackingIsReady:(e,t,n)=>{let r=pV(n);return r&&r.isReady()?1:0},TrackingRefBodyPos:(e,t,n)=>{let r=fV(n);if(!r)return new Float32Array(3);let i=r.getBodyPosW();if(!i)return new Float32Array(3);let a=r.getBodyNames().indexOf(String(t.body??``));return a<0?new Float32Array(3):new Float32Array([i[a*3],i[a*3+1],i[a*3+2]])}};function CV(e,t,n){let r=(e,t)=>typeof e==`boolean`?e:typeof e==`number`?e!==0:e instanceof Uint8Array||e instanceof Float32Array?(e[t]??0)!==0:!1,i=e instanceof Uint8Array||e instanceof Float32Array,a=t instanceof Uint8Array||t instanceof Float32Array;if(!i&&!a)return n(r(e,0),r(t,0));let o=i?e.length:1,s=a?t.length:1,c=Math.max(o,s),l=new Uint8Array(c);for(let i=0;i<c;i++)l[i]=+!!n(r(e,i),r(t,i));return l}function wV(e,t){if(typeof e==`number`)return t(e);if(e instanceof Float32Array){let n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=t(e[r]);return n}return t(lV(e))}function TV(e,t,n){let r=e instanceof Float32Array,i=t instanceof Float32Array;if(!r&&!i)return n(lV(e),lV(t));let a=Math.max(r?e.length:1,i?t.length:1),o=new Float32Array(a);for(let s=0;s<a;s++)o[s]=n(r?e[s]??0:lV(e),i?t[s]??0:lV(t));return o}function EV(e,t,n){let r=e instanceof Float32Array,i=t instanceof Float32Array;if(!r&&!i)return n(lV(e),lV(t));let a=Math.max(r?e.length:1,i?t.length:1),o=new Uint8Array(a);for(let s=0;s<a;s++)o[s]=+!!n(r?e[s]??0:lV(e),i?t[s]??0:lV(t));return o}function DV(e,t,n){if(typeof e==`boolean`)return e;if(typeof e==`number`)return e!==0;let r=n;if(e instanceof Uint8Array){for(let n=0;n<e.length;n++)r=t(r,e[n]!==0);return r}if(e instanceof Float32Array){for(let n=0;n<e.length;n++)r=t(r,e[n]!==0);return r}return r}var OV=class{constructor(){this.states=new Map}get(e){let t=this.states.get(e);return t===void 0&&(t={},this.states.set(e,t)),t}reset(){this.states.clear()}};function kV(e,t,n){let r={};for(let i of e.nodes){let e=SV[i.op];if(e===void 0)throw Error(`DSL interpreter: unknown primitive op "${i.op}". Add it to the engine's primitive registry, or fix the build's serializer.`);let a=(i.in??[]).map(e=>{if(!(e in r))throw Error(`DSL interpreter: node "${i.out}" references unresolved input "${e}". Graph nodes must appear in topological order.`);return r[e]});r[i.out]=e(a,i.attrs??{},t,n.get(i.out))}let i=r[e.output];if(i===void 0)throw Error(`DSL interpreter: graph output "${e.output}" was not produced by any node.`);return i}var AV=class extends MB{constructor(e,t){super(e,t),this.store=new OV,this.graph=t.graph,this.params=t.params??{}}evaluate(e){let t=kV(this.graph,{runner:this.runner,state:e,params:this.params},this.store);return typeof t==`boolean`?t:typeof t==`number`?t!==0:!1}reset(){this.store.reset()}};function jV(e){return`kind`in e&&e.kind===`termination`}var MV=class{constructor(e,t,n){this.terms=[];for(let[r,i]of Object.entries(e)){if(jV(i)){let e={name:r,params:i.params,time_out:i.time_out,graph:{kind:`termination`,nodes:i.nodes,output:i.output}};this.terms.push({name:r,term:new AV(n,e),isTimeOut:i.time_out??!1});continue}let e=t[i.name];if(!e){console.warn(`[TerminationManager] Unknown termination type: ${i.name}`);continue}let a={name:i.name,params:i.params,time_out:i.time_out};this.terms.push({name:r,term:new e(n,a),isTimeOut:i.time_out??!1})}}evaluate(e){let t=!1,n=!1,r=[];for(let{name:i,term:a,isTimeOut:o}of this.terms)a.evaluate(e)&&(r.push(i),o?n=!0:t=!0);return{done:t||n,terminated:t,truncated:n,reasons:r}}reset(){for(let{term:e}of this.terms)e.reset?.()}get size(){return this.terms.length}},NV={},PV=Object.defineProperty,FV=Object.getOwnPropertyDescriptor,IV=Object.getOwnPropertyNames,LV=Object.prototype.hasOwnProperty,RV=(e=>typeof n<`u`?n:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof n<`u`?n:e)[t]}):e)(function(e){if(typeof n<`u`)return n.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),Z=(e,t)=>()=>(e&&(t=e(e=0)),t),zV=(e,t)=>{for(var n in t)PV(e,n,{get:t[n],enumerable:!0})},BV=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of IV(t))!LV.call(e,i)&&i!==n&&PV(e,i,{get:()=>t[i],enumerable:!(r=FV(t,i))||r.enumerable});return e},VV=e=>BV(PV({},`__esModule`,{value:!0}),e),HV,UV,WV,GV,KV,qV=Z(()=>{HV=new Map,UV=[],WV=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=HV.get(e);if(r===void 0)HV.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=UV.indexOf(e);t!==-1&&UV.splice(t,1);for(let t=0;t<UV.length;t++)if(HV.get(UV[t]).priority<=n){UV.splice(t,0,e);return}UV.push(e)}return}throw TypeError(`not a valid backend`)},GV=async e=>{let t=HV.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}}},KV=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?UV:n,i,a=[],o=new Set;for(let e of r){let t=await GV(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)})]}}),JV=Z(()=>{qV()}),YV,XV=Z(()=>{YV=`1.24.3`}),ZV,QV,$V=Z(()=>{XV(),ZV=`warning`,QV={wasm:{},webgl:{},webgpu:{},versions:{common:YV},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}`);ZV=e}},get logLevel(){return ZV}},Object.defineProperty(QV,"logLevel",{enumerable:!0})}),eH,tH=Z(()=>{$V(),eH=QV}),nH,rH,iH=Z(()=>{nH=(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<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}else throw Error(`Can not access image data`)},rH=(e,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<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),aH,oH,sH,cH,lH,uH,dH=Z(()=>{xH(),aH=(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<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new bH(`float32`,u,[1,4,n,r]):new bH(`float32`,u,[1,3,n,r])},oH=async(e,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,aH(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(aH(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return aH(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},sH=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new bH({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},cH=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new bH({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},lH=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new bH({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},uH=(e,t,n)=>new bH({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),fH,pH,mH,hH,gH=Z(()=>{fH=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),pH=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),mH=!1,hH=()=>{if(!mH){mH=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(fH.set(`int64`,BigInt64Array),pH.set(BigInt64Array,`int64`)),t&&(fH.set(`uint64`,BigUint64Array),pH.set(BigUint64Array,`uint64`)),r?(fH.set(`float16`,n),pH.set(n,`float16`)):fH.set(`float16`,Uint16Array)}}}),_H,vH,yH=Z(()=>{xH(),_H=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},vH=(e,t)=>{switch(e.location){case`cpu`:return new bH(e.type,e.data,t);case`cpu-pinned`:return new bH({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new bH({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new bH({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new bH({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),bH,xH=Z(()=>{iH(),dH(),gH(),yH(),bH=class{constructor(e,t,n){hH();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=fH.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=fH.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=pH.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=_H(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 oH(e,t)}static fromTexture(e,t){return sH(e,t)}static fromGpuBuffer(e,t){return cH(e,t)}static fromMLTensor(e,t){return lH(e,t)}static fromPinnedBuffer(e,t,n){return uH(e,t,n)}toDataURL(e){return nH(this,e)}toImageData(e){return rH(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 vH(this,e)}}}),SH,CH=Z(()=>{xH(),SH=bH}),wH,TH,EH,DH,OH,kH,AH=Z(()=>{$V(),wH=(e,t)=>{(typeof QV.trace>`u`?!QV.wasm.trace:!QV.trace)||console.timeStamp(`${e}::ORT::${t}`)},TH=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),wH(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},EH=e=>{(typeof QV.trace>`u`?!QV.wasm.trace:!QV.trace)||TH(`BEGIN`,e)},DH=e=>{(typeof QV.trace>`u`?!QV.wasm.trace:!QV.trace)||TH(`END`,e)},OH=e=>{(typeof QV.trace>`u`?!QV.wasm.trace:!QV.trace)||console.time(`ORT::${e}`)},kH=e=>{(typeof QV.trace>`u`?!QV.wasm.trace:!QV.trace)||console.timeEnd(`ORT::${e}`)}}),jH,MH=Z(()=>{qV(),CH(),AH(),jH=class e{constructor(e){this.handler=e}async run(e,t,n){EH(),OH(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof SH||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 SH)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 SH)&&(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 SH?s[e]=t:s[e]=new SH(t.type,t.data,t.dims)}return kH(`InferenceSession.run`),DH(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){EH(),OH(`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 KV(o),l=await s.createInferenceSessionHandler(a,c);return kH(`InferenceSession.create`),DH(),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}}}),NH,PH=Z(()=>{MH(),NH=jH}),FH=Z(()=>{}),IH=Z(()=>{}),LH=Z(()=>{}),RH=Z(()=>{});zV({},{InferenceSession:()=>NH,TRACE:()=>wH,TRACE_EVENT_BEGIN:()=>OH,TRACE_EVENT_END:()=>kH,TRACE_FUNC_BEGIN:()=>EH,TRACE_FUNC_END:()=>DH,Tensor:()=>SH,env:()=>eH,registerBackend:()=>WV});var zH=Z(()=>{JV(),tH(),PH(),CH(),FH(),IH(),AH(),LH(),RH()}),BH=Z(()=>{}),VH={};zV(VH,{default:()=>WH});var HH,UH,WH,GH=Z(()=>{_$(),xU(),dU(),HH=`ort-wasm-proxy-worker`,UH=globalThis.self?.name===HH,UH&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:yU(n.wasm).then(()=>{a$(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;o$(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=u$(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;d$(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:f$(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;m$(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},g$([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:h$(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),WH=UH?null:e=>new Worker(e??eU,{type:`module`,name:HH})}),KH={};zV(KH,{default:()=>JH});async function qH(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.Zc||=new Map).set(e,n)},t.unmountExternalData=()=>{delete t.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,ae:!0}).buffer.constructor;let a=e=>async(...n)=>{try{if(t.$c)throw Error(`Session already started`);let r=t.$c={Nd:n[0],errors:[]},i=await e(...n);if(t.$c!==r)throw Error(`Session mismatch`);t.gd?.flush();let a=r.errors;if(0<a.length){let e=await Promise.all(a);if(e=e.filter(e=>e),0<e.length)throw Error(e.join(`
12827
12827
  `))}return i}finally{t.$c=null}};t.jsepInit=(e,n)=>{if(e===`webgpu`){[t.gd,t.Dd,t.Hd,t.jd,t.Gd,t.ac,t.Id,t.Kd,t.Ed,t.Fd,t.Jd]=n;let e=t.gd;t.jsepRegisterBuffer=(t,n,r,i)=>e.registerBuffer(t,n,r,i),t.jsepGetBuffer=t=>e.getBuffer(t),t.jsepCreateDownloader=(t,n,r)=>e.createDownloader(t,n,r),t.jsepOnCreateSession=t=>{e.onCreateSession(t)},t.jsepOnReleaseSession=t=>{e.onReleaseSession(t)},t.jsepOnRunStart=t=>e.onRunStart(t),t.Ld=(t,n)=>{e.upload(t,n)}}else if(e===`webnn`){let e=n[0];[t.Zd,t.vd,t.webnnEnsureTensor,t.xd,t.webnnDownloadTensor,t.Yd,t.webnnEnableTraceEvent]=n.slice(1),t.webnnReleaseTensorId=t.vd,t.webnnUploadTensor=t.xd,t.webnnRegisterMLContext=t.Yd,t.webnnOnRunStart=t=>e.onRunStart(t),t.webnnOnRunEnd=e.onRunEnd.bind(e),t.webnnOnReleaseSession=t=>{e.onReleaseSession(t)},t.webnnCreateMLTensorDownloader=(t,n)=>e.createMLTensorDownloader(t,n),t.webnnRegisterMLTensor=(t,n,r,i)=>e.registerMLTensor(t,n,r,i),t.webnnCreateMLContext=t=>e.createMLContext(t),t.webnnRegisterMLConstant=(n,r,i,a,o,s)=>e.registerMLConstant(n,r,i,a,o,t.Zc,s),t.webnnRegisterGraphInput=e.registerGraphInput.bind(e),t.webnnIsGraphInput=e.isGraphInput.bind(e),t.webnnRegisterGraphOutput=e.registerGraphOutput.bind(e),t.webnnIsGraphOutput=e.isGraphOutput.bind(e),t.webnnCreateTemporaryTensor=e.createTemporaryTensor.bind(e),t.webnnIsGraphInputOutputTypeSupported=e.isGraphInputOutputTypeSupported.bind(e)}};let o=()=>{let e=e=>(...t)=>{let n=qt;return t=e(...t),qt==n?t:new Promise((e,t)=>{en={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),a!==void 0&&(t._OrtRun=a(t._OrtRun),t._OrtRunWithBinding=a(t._OrtRunWithBinding)),o=void 0};t.asyncInit=()=>{o?.()};var s,c,l=(e,t)=>{throw t},u=import.meta.url,d=``;if(n||r){try{d=new URL(`.`,u).href}catch{}r&&(c=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),s=async e=>{if(C(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 f,p,m,h,g,_,v=console.log.bind(console),y=console.error.bind(console),b=v,x=y,S=!1,C=e=>e.startsWith(`file://`);function w(){ve.buffer!=E.buffer&&R()}if(i){let e=function(n){try{var r=n.data,i=r.Uc;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),_=()=>{postMessage({Uc:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.Ad)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({Uc:`callHandler`,zd:e,args:t})},e==`print`&&(b=t[e]),e==`printErr`&&(x=t[e]));ve=r.Vd,R(),p=r.Wd,ee(),ua()}else if(i===`run`){(function(e){var t=(w(),j)[e+52>>>2>>>0];e=(w(),j)[e+56>>>2>>>0],Dr(t,t-e),Or(t)})(r.Tc),vr(r.Tc,0,0,1,0,0),he(),It(r.Tc),T||=(mr(),!0);try{ye(r.Pd,r.dd)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?T&&Lt():i&&(x(`worker: received unknown command ${i}`),x(r)))}catch(e){throw yr(),e}};var T=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var E,D,O,k,A,j,M,N,P,F,I,L=!1;function R(){var e=ve.buffer;t.HEAP8=E=new Int8Array(e),O=new Int16Array(e),t.HEAPU8=D=new Uint8Array(e),k=new Uint16Array(e),t.HEAP32=A=new Int32Array(e),t.HEAPU32=j=new Uint32Array(e),M=new Float32Array(e),N=new Float64Array(e),P=new BigInt64Array(e),F=new BigUint64Array(e)}function z(){L=!0,i?_():xi.tb()}function B(e){throw x(e=`Aborted(`+e+`)`),S=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),g?.(e),e}function V(){return{a:{ma:Ti,hb:wi,g:Se,J:we,f:ke,o:Ae,h:je,ha:Me,b:Ne,T:Pe,Ia:Ie,n:Le,_:Ve,Ya:He,Ea:Ue,Ga:We,Za:G,Wa:Ge,Pa:Ke,Va:qe,ka:Je,Fa:Ye,Ca:Xe,Xa:Ze,Da:Qe,cb:$e,ea:st,xa:ct,va:gt,da:vt,O:yt,H:bt,wa:Ct,Z:jt,ya:Mt,Sa:Nt,Aa:Rt,Ja:Bt,ta:Vt,fa:Ht,Ra:It,$a:Ut,R:rn,s:dn,c:dt,ib:fn,y:pn,M:mn,D:hn,m:gn,t:_n,jb:vn,I:yn,S:bn,j:xn,v:Sn,r:Cn,l:wn,Ma:Tn,Na:kn,Oa:An,Ka:jn,La:Mn,ua:Fn,eb:In,bb:zn,u:Hn,aa:Un,ga:Wn,ab:Ln,V:Gn,_a:Kn,Ba:qn,F:Pn,U:Jn,la:$n,za:er,gb:Qn,fb:tr,Ta:ar,Ua:or,Ha:ue,$:sr,ja:cr,Qa:lr,ia:dr,lb:ca,na:ta,mb:sa,oa:ea,G:Gi,d:ki,q:Di,w:Ei,B:zi,pb:Zi,K:Hi,x:ji,pa:Qi,X:na,ba:Xi,nb:oa,ob:aa,ra:Ki,qa:Yi,qb:qi,N:Ui,Y:$i,e:Ai,A:Mi,k:Oi,kb:la,p:Pi,z:Fi,C:Ni,E:Ii,L:Bi,rb:Wi,Q:ra,ca:Vi,W:ia,sb:Ri,sa:Li,P:Ji,i:fr,a:ve,db:ce}}}async function ee(){function e(e,n){var r=xi=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=Gt(n),e[t]=r):e[t]=n;return xi=e,xi=function(){var e=xi,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).ub=t(e.ub),e.Yb=n(e.Yb),e._b=t(e._b),e.mc=t(e.mc),e.nc=n(e.nc),e.rc=t(e.rc),e}(),fe.push(xi.$b),pr=(e=xi).ub,mr=e.vb,t._OrtInit=e.wb,t._OrtGetLastError=e.xb,t._OrtCreateSessionOptions=e.yb,t._OrtAppendExecutionProvider=e.zb,t._OrtAddFreeDimensionOverride=e.Ab,t._OrtAddSessionConfigEntry=e.Bb,t._OrtReleaseSessionOptions=e.Cb,t._OrtCreateSession=e.Db,t._OrtReleaseSession=e.Eb,t._OrtGetInputOutputCount=e.Fb,t._OrtGetInputOutputMetadata=e.Gb,t._OrtFree=e.Hb,t._OrtCreateTensor=e.Ib,t._OrtGetTensorData=e.Jb,t._OrtReleaseTensor=e.Kb,t._OrtCreateRunOptions=e.Lb,t._OrtAddRunConfigEntry=e.Mb,t._OrtReleaseRunOptions=e.Nb,t._OrtCreateBinding=e.Ob,t._OrtBindInput=e.Pb,t._OrtBindOutput=e.Qb,t._OrtClearBoundOutputs=e.Rb,t._OrtReleaseBinding=e.Sb,t._OrtRunWithBinding=e.Tb,t._OrtRun=e.Ub,t._OrtEndProfiling=e.Vb,t._JsepOutput=e.Wb,t._JsepGetNodeName=e.Xb,hr=e.Yb,gr=t._free=e.Zb,_r=t._malloc=e._b,vr=e.bc,yr=e.cc,br=e.dc,xr=e.ec,Sr=e.fc,Cr=e.gc,wr=e.hc,Tr=e.ic,Er=e.jc,Dr=e.kc,Or=e.lc,kr=e.mc,Ar=e.nc,jr=e.oc,Mr=e.pc,K=e.qc,Nr=e.rc,Pr=e.sc,Fr=e.tc,Ir=e.uc,Lr=e.vc,Rr=e.wc,zr=e.xc,Br=e.yc,Vr=e.zc,Hr=e.Ac,Ur=e.Bc,Wr=e.Cc,Gr=e.Dc,Kr=e.Ec,qr=e.Fc,Jr=e.Gc,Yr=e.Hc,Xr=e.Ic,Zr=e.Jc,Qr=e.Kc,$r=e.Lc,ei=e.Mc,ti=e.Nc,ni=e.Oc,ri=e.Pc,ii=e.Rc,ai=e.Sc,oi=e.bd,si=e.cd,ci=e.hd,li=e.kd,ui=e.ld,di=e.md,fi=e.nd,pi=e.od,mi=e.pd,q=e.qd,hi=e.rd,gi=e.wd,_i=e.Rd,vi=e.Sd,yi=e.Td,bi=e.Ud,p=n,xi}var n,r=V();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(p,V()),p):(I??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.jsep.wasm`,d):d+`ort-wasm-simd-threaded.jsep.wasm`:new URL(`/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm`,``+import.meta.url).href,n=await async function(e){var t=I;if(!f&&!C(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){x(`wasm streaming compile failed: ${e}`),x(`falling back to ArrayBuffer instantiation`)}return async function(e,t){try{var n=await async function(e){if(!f)try{var t=await s(e);return new Uint8Array(t)}catch{}if(e==I&&f)e=new Uint8Array(f);else{if(!c)throw`both async and sync fetching of the wasm failed`;e=c(e)}return e}(e);return await WebAssembly.instantiate(n,t)}catch(e){x(`failed to asynchronously prepare wasm: ${e}`),B(e)}}(t,e)}(r),e(n.instance,n.module))}class te{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var ne=e=>{e.terminate(),e.onmessage=()=>{}},re=[],ie=0,ae=null,oe=e=>{U.length==0&&(_e(),ge(U[0]));var t=U.pop();if(!t)return 6;de.push(t),pe[e.Tc]=t,t.Tc=e.Tc;var n={Uc:`run`,Pd:e.Od,dd:e.dd,Tc:e.Tc};return t.postMessage(n,e.ud),0},se=0,H=(e,t,...n)=>{var r,i=16*n.length,a=Ar(),o=kr(i),s=o>>>3;for(r of n)typeof r==`bigint`?((w(),P)[s++>>>0]=1n,(w(),P)[s++>>>0]=r):((w(),P)[s++>>>0]=0n,(w(),N)[s++>>>0]=r);return e=br(e,0,i,o,t),Or(a),e};function ce(e){if(i)return H(0,1,e);if(m=e,!(0<se)){for(var t of de)ne(t);for(t of U)ne(t);U=[],de=[],pe={},S=!0}l(0,new te(e))}function le(e){if(i)return H(1,0,e);ue(e)}var ue=e=>{if(m=e,i)throw le(e),`unwind`;ce(e)},U=[],de=[],fe=[],pe={},me=e=>{var t=e.Tc;delete pe[t],U.push(e),de.splice(de.indexOf(e),1),e.Tc=0,xr(t)};function he(){fe.forEach(e=>e())}var ge=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.Uc,i.ad&&i.ad!=hr()){var a=pe[i.ad];a?a.postMessage(i,i.ud):x(`Internal error! Worker sent a message "${r}" to target pthread ${i.ad}, but that thread no longer exists!`)}else r===`checkMailbox`?Lt():r===`spawnThread`?oe(i):r===`cleanupThread`?Pt(()=>{me(pe[i.Qd])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.zd](...i.args):r&&x(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw x(`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({Uc:`load`,Ad:i,Vd:ve,Wd:p})});function _e(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});U.push(e)}var ve,ye=(e,t)=>{se=0,e=Fr(e,t),0<se?m=e:Sr(e)},be=[],xe=0;function Se(e){var t=new De(e>>>=0);return(w(),E)[t.Vc+12>>>0]==0&&(Te(t,!0),xe--),Ee(t,!1),be.push(t),Nr(e)}var Ce=0,we=()=>{Tr(0,0);var e=be.pop();jr(e.ed),Ce=0};function Te(e,t){t=+!!t,(w(),E)[e.Vc+12>>>0]=t}function Ee(e,t){t=+!!t,(w(),E)[e.Vc+13>>>0]=t}class De{constructor(e){this.ed=e,this.Vc=e-24}}var Oe=e=>{var t=Ce;if(!t)return Er(0),0;var n=new De(t);(w(),j)[n.Vc+16>>>2>>>0]=t;var r=(w(),j)[n.Vc+4>>>2>>>0];if(!r)return Er(0),t;for(var i of e){if(i===0||i===r)break;if(K(i,r,n.Vc+16))return Er(i),t}return Er(r),t};function ke(){return Oe([])}function Ae(e){return Oe([e>>>0])}function je(e,t,n,r){return Oe([e>>>0,t>>>0,n>>>0,r>>>0])}var Me=()=>{var e=be.pop();e||B(`no exception to throw`);var t=e.ed;throw(w(),E)[e.Vc+13>>>0]==0&&(be.push(e),Ee(e,!0),Te(e,!1),xe++),Mr(t),Ce=t};function Ne(e,t,n){var r=new De(e>>>=0);throw t>>>=0,n>>>=0,(w(),j)[r.Vc+16>>>2>>>0]=0,(w(),j)[r.Vc+4>>>2>>>0]=t,(w(),j)[r.Vc+8>>>2>>>0]=n,Mr(e),xe++,Ce=e}var Pe=()=>xe;function Fe(e,t,n,r){return i?H(2,1,e,t,n,r):Ie(e,t,n,r)}function Ie(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?Fe(e,t,n,r):(e={Od:n,Tc:e,dd:r,ud:a},i?(e.Uc=`spawnThread`,postMessage(e,a),0):oe(e))}function Le(e){throw Ce||=e>>>0,Ce}var Re=globalThis.TextDecoder&&new TextDecoder,ze=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},W=(e,t=0,n,r)=>{if(16<(n=ze(e,t>>>=0,n,r))-t&&e.buffer&&Re)return Re.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t<n;){var i=e[t++];if(128&i){var a=63&e[t++];if((224&i)==192)r+=String.fromCharCode((31&i)<<6|a);else{var o=63&e[t++];65536>(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},Be=(e,t,n)=>(e>>>=0)?W((w(),D),e,t,n):``;function Ve(e,t,n){return i?H(3,1,e,t,n):0}function He(e,t){if(i)return H(4,1,e,t)}function Ue(e,t){if(i)return H(5,1,e,t)}function We(e,t,n){if(i)return H(6,1,e,t,n)}function G(e,t,n){return i?H(7,1,e,t,n):0}function Ge(e,t){if(i)return H(8,1,e,t)}function Ke(e,t,n){if(i)return H(9,1,e,t,n)}function qe(e,t,n,r){if(i)return H(10,1,e,t,n,r)}function Je(e,t,n,r){if(i)return H(11,1,e,t,n,r)}function Ye(e,t,n,r){if(i)return H(12,1,e,t,n,r)}function Xe(e){if(i)return H(13,1,e)}function Ze(e,t){if(i)return H(14,1,e,t)}function Qe(e,t,n){if(i)return H(15,1,e,t,n)}var $e=()=>B(``),et=e=>{e>>>=0;for(var t=``;;){var n=(w(),D)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},tt={},nt={},rt={},it=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function at(e,t,n={}){return function(e,t,n={}){var r=t.name;if(!e)throw new it(`type "${r}" must have a positive integer typeid pointer`);if(nt.hasOwnProperty(e)){if(n.Bd)return;throw new it(`Cannot register type '${r}' twice`)}nt[e]=t,delete rt[e],tt.hasOwnProperty(e)&&(t=tt[e],delete tt[e],t.forEach(e=>e()))}(e,t,n)}var ot=(e,t,n)=>{switch(t){case 1:return n?e=>(w(),E)[e>>>0]:e=>(w(),D)[e>>>0];case 2:return n?e=>(w(),O)[e>>>1>>>0]:e=>(w(),k)[e>>>1>>>0];case 4:return n?e=>(w(),A)[e>>>2>>>0]:e=>(w(),j)[e>>>2>>>0];case 8:return n?e=>(w(),P)[e>>>3>>>0]:e=>(w(),F)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function st(e,t,n,r,i){e>>>=0,n>>>=0,t=et(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}at(e,{name:t,Qc:a,Xc:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),Wc:ot(t,n,!r),Yc:null})}function ct(e,t,n,r){at(e>>>=0,{name:t=et(t>>>0),Qc:function(e){return!!e},Xc:function(e,t){return t?n:r},Wc:function(e){return this.Qc((w(),D)[e>>>0])},Yc:null})}var lt=[],ut=[0,1,,1,null,1,!0,1,!1,1];function dt(e){9<(e>>>=0)&&--ut[e+1]==0&&(ut[e]=void 0,lt.push(e))}var ft=e=>{if(!e)throw new it(`Cannot use deleted val. handle = ${e}`);return ut[e]},pt=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=lt.pop()||ut.length;return ut[t]=e,ut[t+1]=1,t}};function mt(e){return this.Qc((w(),j)[e>>>2>>>0])}var ht={name:`emscripten::val`,Qc:e=>{var t=ft(e);return dt(e),t},Xc:(e,t)=>pt(t),Wc:mt,Yc:null};function gt(e){return at(e>>>0,ht)}var _t=(e,t)=>{switch(t){case 4:return function(e){return this.Qc((w(),M)[e>>>2>>>0])};case 8:return function(e){return this.Qc((w(),N)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function vt(e,t,n){n>>>=0,at(e>>>=0,{name:t=et(t>>>0),Qc:e=>e,Xc:(e,t)=>t,Wc:_t(t,n),Yc:null})}function yt(e,t,n,r,i){e>>>=0,n>>>=0,t=et(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<<o>>>o,i=a(i)}at(e,{name:t,Qc:a,Xc:(e,t)=>t,Wc:ot(t,n,r!==0),Yc:null})}function bt(e,t,n){function r(e){var t=(w(),j)[e>>>2>>>0];return e=(w(),j)[e+4>>>2>>>0],new i((w(),E).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];at(e>>>=0,{name:n=et(n>>>0),Qc:r,Wc:r},{Bd:!0})}var xt=(e,t,n)=>{var r=(w(),D);if(t>>>=0,0<n){var i=t;n=t+n-1;for(var a=0;a<e.length;++a){var o=e.codePointAt(a);if(127>=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},St=e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function Ct(e,t){at(e>>>=0,{name:t=et(t>>>0),Qc(e){var t=(w(),j)[e>>>2>>>0];return t=Be(e+4,t,!0),gr(e),t},Xc(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 it(`Cannot pass non-string to std::string`);var r=n?St(t):t.length,i=_r(4+r+1),a=i+4;return(w(),j)[i>>>2>>>0]=r,n?xt(t,a,r+1):(w(),D).set(t,a>>>0),e!==null&&e.push(gr,i),i},Wc:mt,Yc(e){gr(e)}})}var wt=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,Tt=(e,t,n)=>{if(e>>>=1,16<(t=ze((w(),k),e,t/2,n))-e&&wt)return wt.decode((w(),k).slice(e,t));for(n=``;e<t;++e){var r=(w(),k)[e>>>0];n+=String.fromCharCode(r)}return n},Et=(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<n;++i){var a=e.charCodeAt(i);(w(),O)[t>>>1>>>0]=a,t+=2}return(w(),O)[t>>>1>>>0]=0,t-r},Dt=e=>2*e.length,Ot=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(w(),j)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},kt=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i<e.length;++i){var a=e.codePointAt(i);if(65535<a&&i++,(w(),A)[t>>>2>>>0]=a,(t+=4)+4>n)break}return(w(),A)[t>>>2>>>0]=0,t-r},At=e=>{for(var t=0,n=0;n<e.length;++n)65535<e.codePointAt(n)&&n++,t+=4;return t};function jt(e,t,n){if(e>>>=0,t>>>=0,n=et(n>>>=0),t===2)var r=Tt,i=Et,a=Dt;else r=Ot,i=kt,a=At;at(e,{name:n,Qc:e=>{var n=(w(),j)[e>>>2>>>0];return n=r(e+4,n*t,!0),gr(e),n},Xc:(e,r)=>{if(typeof r!=`string`)throw new it(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=_r(4+o+t);return(w(),j)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(gr,s),s},Wc:mt,Yc(e){gr(e)}})}function Mt(e,t){at(e>>>=0,{Cd:!0,name:t=et(t>>>0),Qc:()=>{},Xc:()=>{}})}function Nt(e){vr(e>>>0,!r,1,!n,131072,!1),he()}var Pt=e=>{if(!S)try{if(e(),!(0<se))try{i?hr()&&Sr(m):ue(m)}catch(e){e instanceof te||e==`unwind`||l(0,e)}}catch(e){e instanceof te||e==`unwind`||l(0,e)}},Ft=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function It(e){e>>>=0,Ft||(Atomics.waitAsync((w(),A),e>>>2,e).value.then(Lt),e+=128,Atomics.store((w(),A),e>>>2,1))}var Lt=()=>Pt(()=>{var e=hr();e&&(It(e),wr())});function Rt(e,t){(e>>>=0)==t>>>0?setTimeout(Lt):i?postMessage({ad:e,Uc:`checkMailbox`}):(e=pe[e])&&e.postMessage({Uc:`checkMailbox`})}var zt=[];function Bt(e,t,n,r,i){for(t>>>=0,i>>>=0,zt.length=0,n=i>>>3,r=i+r>>>3;n<r;){var a=(w(),P)[n++>>>0]?(w(),P)[n++>>>0]:(w(),N)[n++>>>0];zt.push(a)}return(t?Ci[t]:Si[e])(...zt)}var Vt=()=>{se=0};function Ht(e){e>>>=0,i?postMessage({Uc:`cleanupThread`,Qd:e}):me(pe[e])}function Ut(e){}var Wt=e=>{try{e()}catch(e){B(e)}};function Gt(e){var t=(...t)=>{Yt.push(e);try{return e(...t)}finally{S||(Yt.pop(),qt&&Kt===1&&Yt.length===0&&(Kt=0,se+=1,Wt(vi),typeof Fibers<`u`&&Fibers.ce()))}};return Qt.set(e,t),t}var Kt=0,qt=null,Jt=0,Yt=[],Xt=new Map,Zt=new Map,Qt=new Map,$t=0,en=null,tn=[],nn=e=>function(e){if(!S){if(Kt===0){var t=!1,n=!1;e((e=0)=>{if(!S&&(Jt=e,t=!0,n)){Kt=2,Wt(()=>yi(qt)),typeof MainLoop<`u`&&MainLoop.yd&&MainLoop.resume(),e=!1;try{var r=function(){var e=(w(),A)[qt+8>>>2>>>0];return e=Zt.get(e),e=Qt.get(e),--se,e()}()}catch(t){r=t,e=!0}var i=!1;if(!qt){var a=en;a&&(en=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(Kt=1,qt=function(){var e=_r(65548),t=e+12;if((w(),j)[e>>>2>>>0]=t,(w(),j)[e+4>>>2>>>0]=t+65536,t=Yt[0],!Xt.has(t)){var n=$t++;Xt.set(t,n),Zt.set(n,t)}return t=Xt.get(t),(w(),A)[e+8>>>2>>>0]=t,e}(),typeof MainLoop<`u`&&MainLoop.yd&&MainLoop.pause(),Wt(()=>_i(qt)))}else Kt===2?(Kt=0,Wt(bi),gr(qt),qt=null,tn.forEach(Pt)):B(`invalid state: ${Kt}`);return Jt}}(t=>{e().then(t)});function rn(e){return e>>>=0,nn(async()=>pt(await ft(e)))}var an=[],on=e=>{var t=an.length;return an.push(e),t},sn=(e,t)=>{for(var n=Array(e),r=0;r<e;++r){var i=r,a=(w(),j)[t+4*r>>>2>>>0],o=nt[a];if(o===void 0)throw e=`parameter ${r}`,a=pr(a),t=et(a),gr(a),new it(`${e} has unknown type ${t}`);n[i]=o}return n},cn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((w(),j)[t>>>2>>>0]=pt(r)),e},ln={},un=e=>{var t=ln[e];return t===void 0?et(e):t};function dn(e,t,n){var[r,...i]=sn(e,t>>>0);t=r.Xc.bind(r);var a=i.map(e=>e.Wc.bind(e));e--;var o={toValue:ft};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=un,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.Cd||(o.toReturnWire=t,o.emval_returnValue=cn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) {
12828
12828
  ${s}
12829
12829
  }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,on(Object.defineProperty(n,"name",{value:s}))}function fn(e,t){return t>>>=0,(e=ft(e>>>0))==ft(t)}function pn(e){return(e>>>=0)?(e=un(e),pt(globalThis[e])):pt(globalThis)}function mn(e){return e=un(e>>>0),pt(t[e])}function hn(e,t){return t>>>=0,e=ft(e>>>0),t=ft(t),pt(e[t])}function gn(e){9<(e>>>=0)&&(ut[e+1]+=1)}function _n(e,t,n,r,i){return an[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function vn(e,t,n,r,i){return _n(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function yn(){return pt([])}function bn(e){e=ft(e>>>0);for(var t=Array(e.length),n=0;n<e.length;n++)t[n]=e[n];return pt(t)}function xn(e){return pt(un(e>>>0))}function Sn(){return pt({})}function Cn(e){for(var t=ft(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}dt(e)}function wn(e,t,n){t>>>=0,n>>>=0,e=ft(e>>>0),t=ft(t),n=ft(n),e[t]=n}function Tn(e,t){e=-9007199254740992>e||9007199254740992<e?NaN:Number(e),t>>>=0,e=new Date(1e3*e),(w(),A)[t>>>2>>>0]=e.getUTCSeconds(),(w(),A)[t+4>>>2>>>0]=e.getUTCMinutes(),(w(),A)[t+8>>>2>>>0]=e.getUTCHours(),(w(),A)[t+12>>>2>>>0]=e.getUTCDate(),(w(),A)[t+16>>>2>>>0]=e.getUTCMonth(),(w(),A)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(w(),A)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(w(),A)[t+28>>>2>>>0]=e}var En=e=>e%4==0&&(e%100!=0||e%400==0),Dn=[0,31,60,91,121,152,182,213,244,274,305,335],On=[0,31,59,90,120,151,181,212,243,273,304,334];function kn(e,t){e=-9007199254740992>e||9007199254740992<e?NaN:Number(e),t>>>=0,e=new Date(1e3*e),(w(),A)[t>>>2>>>0]=e.getSeconds(),(w(),A)[t+4>>>2>>>0]=e.getMinutes(),(w(),A)[t+8>>>2>>>0]=e.getHours(),(w(),A)[t+12>>>2>>>0]=e.getDate(),(w(),A)[t+16>>>2>>>0]=e.getMonth(),(w(),A)[t+20>>>2>>>0]=e.getFullYear()-1900,(w(),A)[t+24>>>2>>>0]=e.getDay();var n=(En(e.getFullYear())?Dn:On)[e.getMonth()]+e.getDate()-1|0;(w(),A)[t+28>>>2>>>0]=n,(w(),A)[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)),(w(),A)[t+32>>>2>>>0]=e}function An(e){e>>>=0;var t=new Date((w(),A)[e+20>>>2>>>0]+1900,(w(),A)[e+16>>>2>>>0],(w(),A)[e+12>>>2>>>0],(w(),A)[e+8>>>2>>>0],(w(),A)[e+4>>>2>>>0],(w(),A)[e>>>2>>>0],0),n=(w(),A)[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?(w(),A)[e+32>>>2>>>0]=+(i!=a&&o==r):0<n!=(o==r)&&(i=Math.max(a,i),t.setTime(t.getTime()+6e4*((0<n?o:i)-r))),(w(),A)[e+24>>>2>>>0]=t.getDay(),n=(En(t.getFullYear())?Dn:On)[t.getMonth()]+t.getDate()-1|0,(w(),A)[e+28>>>2>>>0]=n,(w(),A)[e>>>2>>>0]=t.getSeconds(),(w(),A)[e+4>>>2>>>0]=t.getMinutes(),(w(),A)[e+8>>>2>>>0]=t.getHours(),(w(),A)[e+12>>>2>>>0]=t.getDate(),(w(),A)[e+16>>>2>>>0]=t.getMonth(),(w(),A)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function jn(e,t,n,r,a,o,s){return i?H(16,1,e,t,n,r,a,o,s):-52}function Mn(e,t,n,r,a,o){if(i)return H(17,1,e,t,n,r,a,o)}var Nn={},Pn=()=>performance.timeOrigin+performance.now();function Fn(e,t){return i?H(18,1,e,t):(Nn[e]&&(clearTimeout(Nn[e].id),delete Nn[e]),t&&(Nn[e]={id:setTimeout(()=>{delete Nn[e],Pt(()=>Cr(e,performance.timeOrigin+performance.now()))},t),be:t}),0)}function In(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);(w(),j)[e>>>2>>>0]=60*o,(w(),A)[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),i<a?(xt(e,n,17),xt(t,r,17)):(xt(e,r,17),xt(t,n,17))}var Ln=()=>Date.now(),Rn=1;function zn(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!Rn)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(w(),P)[n>>>3>>>0]=BigInt(e),0}var Bn=[],Vn=(e,t)=>{Bn.length=0;for(var n;n=(w(),D)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,Bn.push(n==112?(w(),j)[t>>>2>>>0]:n==106?(w(),P)[t>>>3>>>0]:n==105?(w(),A)[t>>>2>>>0]:(w(),N)[t>>>3>>>0]),t+=r?8:4}return Bn};function Hn(e,t,n){return e>>>=0,t=Vn(t>>>0,n>>>0),Ci[e](...t)}function Un(e,t,n){return e>>>=0,t=Vn(t>>>0,n>>>0),Ci[e](...t)}var Wn=()=>{};function Gn(e,t){return x(Be(e>>>0,t>>>0))}var Kn=()=>{throw se+=1,`unwind`};function qn(){return 4294901760}var Jn=()=>navigator.hardwareConcurrency,Yn={},Xn=e=>{var t;return(t=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(e))?+t[1]:(t=/:(\d+):\d+(?:\)|$)/.exec(e))?2147483648|t[1]:0},Zn=e=>{for(var t of e)(e=Xn(t))&&(Yn[e]=t)};function Qn(){var e=Error().stack.toString().split(`
12830
12830
  `);return e[0]==`Error`&&e.shift(),Zn(e),Yn.sd=Xn(e[3]),Yn.Md=e,Yn.sd}function $n(e){if(!(e=Yn[e>>>0]))return 0;var t;if(t=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(e))e=t[1];else if(t=/^\s+at (.*) \(.*\)$/.exec(e))e=t[1];else{if(!(t=/^(.+?)@/.exec(e)))return 0;e=t[1]}gr($n.td??0),t=St(e)+1;var n=_r(t);return n&&xt(e,n,t),$n.td=n,$n.td}function er(e){e>>>=0;var t=(w(),D).length;if(e<=t||4294901760<e)return!1;for(var n=1;4>=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))-ve.buffer.byteLength+65535)/65536|0;try{ve.grow(r),R();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}function tr(e,t,n){if(e>>>=0,t>>>=0,Yn.sd==e)var r=Yn.Md;else (r=Error().stack.toString().split(`
12831
- `))[0]==`Error`&&r.shift(),Zn(r);for(var i=3;r[i]&&Xn(r[i])!=e;)++i;for(e=0;e<n&&r[e+i];++e)(w(),A)[t+4*e>>>2>>>0]=Xn(r[e+i]);return e}var nr,rr={},ir=()=>{if(!nr){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]}`);nr=n}return nr};function ar(e,t){if(i)return H(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of ir()){var o=t+r;(w(),j)[e+a>>>2>>>0]=o,r+=xt(n,o,1/0)+1,a+=4}return 0}function or(e,t){if(i)return H(20,1,e,t);e>>>=0,t>>>=0;var n=ir();for(var r of((w(),j)[e>>>2>>>0]=n.length,e=0,n))e+=St(r)+1;return(w(),j)[t>>>2>>>0]=e,0}function sr(e){return i?H(21,1,e):52}function cr(e,t,n,r){return i?H(22,1,e,t,n,r):52}function lr(e,t,n,r){return i?H(23,1,e,t,n,r):70}var ur=[null,[],[]];function dr(e,t,n,r){if(i)return H(24,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o<n;o++){var s=(w(),j)[t>>>2>>>0],c=(w(),j)[t+4>>>2>>>0];t+=8;for(var l=0;l<c;l++){var u=e,d=(w(),D)[s+l>>>0],f=ur[u];d===0||d===10?((u===1?b:x)(W(f)),f.length=0):f.push(d)}a+=c}return(w(),j)[r>>>2>>>0]=a,0}function fr(e){return e>>>0}i||function(){for(var e=t.numThreads-1;e--;)_e();re.push(async()=>{var e=async function(){if(!i)return Promise.all(U.map(ge))}();ie++,await e,--ie==0&&ae&&(e=ae,ae=null,e())})}(),i||(ve=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),R()),t.wasmBinary&&(f=t.wasmBinary),t.stackSave=()=>Ar(),t.stackRestore=e=>Or(e),t.stackAlloc=e=>kr(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(w(),E)[e>>>0]=t;break;case`i16`:(w(),O)[e>>>1>>>0]=t;break;case`i32`:(w(),A)[e>>>2>>>0]=t;break;case`i64`:(w(),P)[e>>>3>>>0]=BigInt(t);break;case`float`:(w(),M)[e>>>2>>>0]=t;break;case`double`:(w(),N)[e>>>3>>>0]=t;break;case`*`:(w(),j)[e>>>2>>>0]=t;break;default:B(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(w(),E)[e>>>0];case`i16`:return(w(),O)[e>>>1>>>0];case`i32`:return(w(),A)[e>>>2>>>0];case`i64`:return(w(),P)[e>>>3>>>0];case`float`:return(w(),M)[e>>>2>>>0];case`double`:return(w(),N)[e>>>3>>>0];case`*`:return(w(),j)[e>>>2>>>0];default:B(`invalid type for getValue: ${t}`)}},t.UTF8ToString=Be,t.stringToUTF8=xt,t.lengthBytesUTF8=St;var pr,mr,hr,gr,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,K,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,q,hi,gi,_i,vi,yi,bi,xi,Si=[ce,le,Fe,Ve,He,Ue,We,G,Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,jn,Mn,Fn,ar,or,sr,cr,lr,dr],Ci={929356:(e,n,r,i,a)=>{if(t===void 0||!t.Zc)return 1;if((e=Be(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.Zc.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:(w(),D).set(o,i>>>0);break;case 1:t.Xd?t.Xd(i,o):t.Ld(i,o);break;default:return 4}return 0}catch{return 4}},930180:(e,n,r)=>{t.xd(e,(w(),D).subarray(n>>>0,n+r>>>0))},930244:()=>t.Zd(),930286:e=>{t.vd(e)},930323:()=>{t.Ed()},930354:()=>{t.Fd()},930383:()=>{t.Jd()},930408:e=>t.Dd(e),930441:e=>t.Hd(e),930473:(e,n,r)=>{t.jd(Number(e),Number(n),Number(r),!0)},930536:(e,n,r)=>{t.jd(Number(e),Number(n),Number(r))},930593:()=>typeof wasmOffsetConverter<`u`,930650:e=>{t.ac(`Abs`,e,void 0)},930701:e=>{t.ac(`Neg`,e,void 0)},930752:e=>{t.ac(`Floor`,e,void 0)},930805:e=>{t.ac(`Ceil`,e,void 0)},930857:e=>{t.ac(`Reciprocal`,e,void 0)},930915:e=>{t.ac(`Sqrt`,e,void 0)},930967:e=>{t.ac(`Exp`,e,void 0)},931018:e=>{t.ac(`Erf`,e,void 0)},931069:e=>{t.ac(`Sigmoid`,e,void 0)},931124:(e,n,r)=>{t.ac(`HardSigmoid`,e,{alpha:n,beta:r})},931203:e=>{t.ac(`Log`,e,void 0)},931254:e=>{t.ac(`Sin`,e,void 0)},931305:e=>{t.ac(`Cos`,e,void 0)},931356:e=>{t.ac(`Tan`,e,void 0)},931407:e=>{t.ac(`Asin`,e,void 0)},931459:e=>{t.ac(`Acos`,e,void 0)},931511:e=>{t.ac(`Atan`,e,void 0)},931563:e=>{t.ac(`Sinh`,e,void 0)},931615:e=>{t.ac(`Cosh`,e,void 0)},931667:e=>{t.ac(`Asinh`,e,void 0)},931720:e=>{t.ac(`Acosh`,e,void 0)},931773:e=>{t.ac(`Atanh`,e,void 0)},931826:e=>{t.ac(`Tanh`,e,void 0)},931878:e=>{t.ac(`Not`,e,void 0)},931929:(e,n,r)=>{t.ac(`Clip`,e,{min:n,max:r})},931998:e=>{t.ac(`Clip`,e,void 0)},932050:(e,n)=>{t.ac(`Elu`,e,{alpha:n})},932108:e=>{t.ac(`Gelu`,e,void 0)},932160:e=>{t.ac(`Relu`,e,void 0)},932212:(e,n)=>{t.ac(`LeakyRelu`,e,{alpha:n})},932276:(e,n)=>{t.ac(`ThresholdedRelu`,e,{alpha:n})},932346:(e,n)=>{t.ac(`Cast`,e,{to:n})},932404:e=>{t.ac(`Add`,e,void 0)},932455:e=>{t.ac(`Sub`,e,void 0)},932506:e=>{t.ac(`Mul`,e,void 0)},932557:e=>{t.ac(`Div`,e,void 0)},932608:e=>{t.ac(`Pow`,e,void 0)},932659:e=>{t.ac(`Equal`,e,void 0)},932712:e=>{t.ac(`Greater`,e,void 0)},932767:e=>{t.ac(`GreaterOrEqual`,e,void 0)},932829:e=>{t.ac(`Less`,e,void 0)},932881:e=>{t.ac(`LessOrEqual`,e,void 0)},932940:(e,n,r,i,a)=>{t.ac(`ReduceMean`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933115:(e,n,r,i,a)=>{t.ac(`ReduceMax`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933289:(e,n,r,i,a)=>{t.ac(`ReduceMin`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933463:(e,n,r,i,a)=>{t.ac(`ReduceProd`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933638:(e,n,r,i,a)=>{t.ac(`ReduceSum`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933812:(e,n,r,i,a)=>{t.ac(`ReduceL1`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933985:(e,n,r,i,a)=>{t.ac(`ReduceL2`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934158:(e,n,r,i,a)=>{t.ac(`ReduceLogSum`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934335:(e,n,r,i,a)=>{t.ac(`ReduceSumSquare`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934515:(e,n,r,i,a)=>{t.ac(`ReduceLogSumExp`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934695:e=>{t.ac(`Where`,e,void 0)},934748:(e,n,r)=>{t.ac(`Transpose`,e,{perm:n?Array.from((w(),A).subarray(Number(n)>>>0,Number(r)>>>0)):[]})},934872:(e,n,r,i)=>{t.ac(`DepthToSpace`,e,{blocksize:n,mode:Be(r),format:i?`NHWC`:`NCHW`})},935005:(e,n,r,i)=>{t.ac(`DepthToSpace`,e,{blocksize:n,mode:Be(r),format:i?`NHWC`:`NCHW`})},935138:(e,n,r,i,a,o,s,c,l,u,d,f,p,m,h)=>{t.ac(`ConvTranspose`,e,{format:l?`NHWC`:`NCHW`,autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,s],strides:[c],wIsConst:()=>!!(w(),E)[u>>>0],outputPadding:d?Array.from((w(),A).subarray(Number(d)>>>0,Number(f)>>>0)):[],outputShape:p?Array.from((w(),A).subarray(Number(p)>>>0,Number(m)>>>0)):[],activation:Be(h)})},935571:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`ConvTranspose`,e,{format:c?`NHWC`:`NCHW`,autoPad:n,dilations:Array.from((w(),A).subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from((w(),A).subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from((w(),A).subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from((w(),A).subarray(Number(s)>>>0,2+(Number(s)>>>0)>>>0)),wIsConst:()=>!!(w(),E)[l>>>0],outputPadding:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],outputShape:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[],activation:Be(m)})},936232:(e,n,r,i,a,o,s,c,l,u,d,f,p,m,h)=>{t.ac(`ConvTranspose`,e,{format:l?`NHWC`:`NCHW`,autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,s],strides:[c],wIsConst:()=>!!(w(),E)[u>>>0],outputPadding:d?Array.from((w(),A).subarray(Number(d)>>>0,Number(f)>>>0)):[],outputShape:p?Array.from((w(),A).subarray(Number(p)>>>0,Number(m)>>>0)):[],activation:Be(h)})},936665:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`ConvTranspose`,e,{format:c?`NHWC`:`NCHW`,autoPad:n,dilations:Array.from((w(),A).subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from((w(),A).subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from((w(),A).subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from((w(),A).subarray(Number(s)>>>0,2+(Number(s)>>>0)>>>0)),wIsConst:()=>!!(w(),E)[l>>>0],outputPadding:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],outputShape:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[],activation:Be(m)})},937326:(e,n)=>{t.ac(`GlobalAveragePool`,e,{format:n?`NHWC`:`NCHW`})},937417:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`AveragePool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},937896:(e,n)=>{t.ac(`GlobalAveragePool`,e,{format:n?`NHWC`:`NCHW`})},937987:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`AveragePool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},938466:(e,n)=>{t.ac(`GlobalMaxPool`,e,{format:n?`NHWC`:`NCHW`})},938553:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`MaxPool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},939028:(e,n)=>{t.ac(`GlobalMaxPool`,e,{format:n?`NHWC`:`NCHW`})},939115:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`MaxPool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},939590:(e,n,r,i,a)=>{t.ac(`Gemm`,e,{alpha:n,beta:r,transA:i,transB:a})},939694:e=>{t.ac(`MatMul`,e,void 0)},939748:(e,n,r,i)=>{t.ac(`ArgMax`,e,{keepDims:!!n,selectLastIndex:!!r,axis:i})},939856:(e,n,r,i)=>{t.ac(`ArgMin`,e,{keepDims:!!n,selectLastIndex:!!r,axis:i})},939964:(e,n)=>{t.ac(`Softmax`,e,{axis:n})},940027:(e,n)=>{t.ac(`Concat`,e,{axis:n})},940087:(e,n,r,i,a)=>{t.ac(`Split`,e,{axis:n,numOutputs:r,splitSizes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},940243:e=>{t.ac(`Expand`,e,void 0)},940297:(e,n)=>{t.ac(`Gather`,e,{axis:Number(n)})},940368:(e,n)=>{t.ac(`GatherElements`,e,{axis:Number(n)})},940447:(e,n)=>{t.ac(`GatherND`,e,{batch_dims:Number(n)})},940526:(e,n,r,i,a,o,s,c,l,u,d)=>{t.ac(`Resize`,e,{antialias:n,axes:r?Array.from((w(),A).subarray(Number(r)>>>0,Number(i)>>>0)):[],coordinateTransformMode:Be(a),cubicCoeffA:o,excludeOutside:s,extrapolationValue:c,keepAspectRatioPolicy:Be(l),mode:Be(u),nearestMode:Be(d)})},940888:(e,n,r,i,a,o,s)=>{t.ac(`Slice`,e,{starts:n?Array.from((w(),A).subarray(Number(n)>>>0,Number(r)>>>0)):[],ends:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[],axes:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[]})},941152:e=>{t.ac(`Tile`,e,void 0)},941204:(e,n,r)=>{t.ac(`InstanceNormalization`,e,{epsilon:n,format:r?`NHWC`:`NCHW`})},941318:(e,n,r)=>{t.ac(`InstanceNormalization`,e,{epsilon:n,format:r?`NHWC`:`NCHW`})},941432:e=>{t.ac(`Range`,e,void 0)},941485:(e,n)=>{t.ac(`Einsum`,e,{equation:Be(n)})},941566:(e,n,r,i,a)=>{t.ac(`Pad`,e,{mode:n,value:r,pads:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},941709:(e,n,r,i,a,o)=>{t.ac(`BatchNormalization`,e,{epsilon:n,momentum:r,spatial:!!a,trainingMode:!!i,format:o?`NHWC`:`NCHW`})},941878:(e,n,r,i,a,o)=>{t.ac(`BatchNormalization`,e,{epsilon:n,momentum:r,spatial:!!a,trainingMode:!!i,format:o?`NHWC`:`NCHW`})},942047:(e,n,r)=>{t.ac(`CumSum`,e,{exclusive:Number(n),reverse:Number(r)})},942144:(e,n,r)=>{t.ac(`DequantizeLinear`,e,{axis:n,blockSize:r})},942234:(e,n,r,i,a)=>{t.ac(`GridSample`,e,{align_corners:n,mode:Be(r),padding_mode:Be(i),format:a?`NHWC`:`NCHW`})},942404:(e,n,r,i,a)=>{t.ac(`GridSample`,e,{align_corners:n,mode:Be(r),padding_mode:Be(i),format:a?`NHWC`:`NCHW`})},942574:(e,n)=>{t.ac(`ScatterND`,e,{reduction:Be(n)})},942659:(e,n,r,i,a,o,s,c,l)=>{t.ac(`Attention`,e,{numHeads:n,isUnidirectional:r,maskFilterValue:i,scale:a,doRotary:o,qkvHiddenSizes:s?Array.from((w(),A).subarray(Number(c)>>>0,Number(c)+s>>>0)):[],pastPresentShareBuffer:!!l})},942931:e=>{t.ac(`BiasAdd`,e,void 0)},942986:e=>{t.ac(`BiasSplitGelu`,e,void 0)},943047:e=>{t.ac(`FastGelu`,e,void 0)},943103:(e,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g)=>{t.ac(`Conv`,e,{format:f?`NHWC`:`NCHW`,auto_pad:n,dilations:r?Array.from((w(),A).subarray(Number(r)>>>0,Number(i)>>>0)):[],group:a,kernel_shape:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],pads:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],strides:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],w_is_const:()=>!!(w(),E)[Number(p)>>>0],activation:Be(m),activation_params:h?Array.from((w(),M).subarray(Number(h)>>>0,Number(g)>>>0)):[]})},943687:e=>{t.ac(`Gelu`,e,void 0)},943739:(e,n,r,i,a,o,s,c,l)=>{t.ac(`GroupQueryAttention`,e,{numHeads:n,kvNumHeads:r,scale:i,softcap:a,doRotary:o,rotaryInterleaved:s,smoothSoftmax:c,localWindowSize:l})},943956:(e,n,r,i)=>{t.ac(`LayerNormalization`,e,{axis:n,epsilon:r,simplified:!!i})},944067:(e,n,r,i)=>{t.ac(`LayerNormalization`,e,{axis:n,epsilon:r,simplified:!!i})},944178:(e,n,r,i,a,o)=>{t.ac(`MatMulNBits`,e,{k:n,n:r,accuracyLevel:i,bits:a,blockSize:o})},944305:(e,n,r,i,a,o)=>{t.ac(`MultiHeadAttention`,e,{numHeads:n,isUnidirectional:r,maskFilterValue:i,scale:a,doRotary:o})},944464:(e,n)=>{t.ac(`QuickGelu`,e,{alpha:n})},944528:(e,n,r,i,a)=>{t.ac(`RotaryEmbedding`,e,{interleaved:!!n,numHeads:r,rotaryEmbeddingDim:i,scale:a})},944667:(e,n,r)=>{t.ac(`SkipLayerNormalization`,e,{epsilon:n,simplified:!!r})},944769:(e,n,r)=>{t.ac(`SkipLayerNormalization`,e,{epsilon:n,simplified:!!r})},944871:(e,n,r,i)=>{t.ac(`GatherBlockQuantized`,e,{gatherAxis:n,quantizeAxis:r,blockSize:i})},944992:e=>{t.Id(e)},945026:(e,n)=>t.Kd(Number(e),Number(n),t.$c.Nd,t.$c.errors)};function wi(e,n,r){return nn(async()=>{await t.Gd(Number(e),Number(n),Number(r))})}function Ti(){return typeof wasmOffsetConverter<`u`}function Ei(e,t,n,r){var i=Ar();try{return Ur(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function Di(e,t,n){var r=Ar();try{return zr(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function Oi(e,t,n){var r=Ar();try{Pr(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function ki(e,t){var n=Ar();try{return Fr(e,t)}catch(e){if(Or(n),e!==e+0)throw e;Tr(1,0)}}function Ai(e){var t=Ar();try{Ir(e)}catch(e){if(Or(t),e!==e+0)throw e;Tr(1,0)}}function ji(e,t,n,r,i,a,o){var s=Ar();try{return Vr(e,t,n,r,i,a,o)}catch(e){if(Or(s),e!==e+0)throw e;Tr(1,0)}}function Mi(e,t){var n=Ar();try{Wr(e,t)}catch(e){if(Or(n),e!==e+0)throw e;Tr(1,0)}}function Ni(e,t,n,r,i,a){var o=Ar();try{Lr(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Pi(e,t,n,r){var i=Ar();try{Hr(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function Fi(e,t,n,r,i){var a=Ar();try{Rr(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function Ii(e,t,n,r,i,a,o){var s=Ar();try{Kr(e,t,n,r,i,a,o)}catch(e){if(Or(s),e!==e+0)throw e;Tr(1,0)}}function Li(e,t,n,r,i,a,o){var s=Ar();try{qr(e,t,n,r,i,a,o)}catch(e){if(Or(s),e!==e+0)throw e;Tr(1,0)}}function Ri(e,t,n,r,i,a,o,s){var c=Ar();try{Zr(e,t,n,r,i,a,o,s)}catch(e){if(Or(c),e!==e+0)throw e;Tr(1,0)}}function zi(e,t,n,r,i){var a=Ar();try{return Gr(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function Bi(e,t,n,r,i,a,o,s){var c=Ar();try{Qr(e,t,n,r,i,a,o,s)}catch(e){if(Or(c),e!==e+0)throw e;Tr(1,0)}}function Vi(e,t,n,r,i,a,o,s,c,l,u,d){var f=Ar();try{Jr(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(Or(f),e!==e+0)throw e;Tr(1,0)}}function Hi(e,t,n,r,i,a){var o=Ar();try{return Yr(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Ui(e,t,n){var r=Ar();try{return $r(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;return Tr(1,0),0n}}function Wi(e,t,n,r,i,a,o,s,c){var l=Ar();try{Br(e,t,n,r,i,a,o,s,c)}catch(e){if(Or(l),e!==e+0)throw e;Tr(1,0)}}function Gi(e){var t=Ar();try{return ei(e)}catch(e){if(Or(t),e!==e+0)throw e;Tr(1,0)}}function Ki(e,t,n){var r=Ar();try{return ti(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function qi(e,t){var n=Ar();try{return gi(e,t)}catch(e){if(Or(n),e!==e+0)throw e;return Tr(1,0),0n}}function Ji(e,t,n,r,i){var a=Ar();try{ni(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function Yi(e){var t=Ar();try{return ri(e)}catch(e){if(Or(t),e!==e+0)throw e;return Tr(1,0),0n}}function Xi(e,t,n,r,i,a){var o=Ar();try{return li(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Zi(e,t,n,r,i,a){var o=Ar();try{return ui(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Qi(e,t,n,r,i,a,o,s){var c=Ar();try{return Xr(e,t,n,r,i,a,o,s)}catch(e){if(Or(c),e!==e+0)throw e;Tr(1,0)}}function $i(e,t,n,r,i){var a=Ar();try{return di(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;return Tr(1,0),0n}}function ea(e,t,n,r){var i=Ar();try{return fi(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function ta(e,t,n,r){var i=Ar();try{return pi(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function na(e,t,n,r,i,a,o,s,c,l,u,d){var f=Ar();try{return mi(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(Or(f),e!==e+0)throw e;Tr(1,0)}}function ra(e,t,n,r,i,a,o,s,c,l,u){var d=Ar();try{si(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(Or(d),e!==e+0)throw e;Tr(1,0)}}function ia(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=Ar();try{ci(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(Or(g),e!==e+0)throw e;Tr(1,0)}}function aa(e,t,n,r){var i=Ar();try{return q(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function oa(e,t,n,r,i){var a=Ar();try{return hi(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function sa(e,t,n){var r=Ar();try{return ii(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function ca(e,t,n){var r=Ar();try{return ai(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function la(e,t,n,r){var i=Ar();try{oi(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function ua(){if(0<ie)ae=ua;else if(i)h?.(t),z();else{for(var e=re;0<e.length;)e.shift()(t);0<ie?ae=ua:(t.calledRun=!0,S||(z(),h?.(t)))}}return i||(xi=await ee(),ua()),t.PTR_SIZE=4,L?t:new Promise((e,t)=>{h=e,g=t})}var KH,qH,JH=Z(()=>{KH=GH,qH=globalThis.self?.name?.startsWith(`em-pthread`),qH&&GH()}),YH,XH,ZH,QH,$H,eU,tU,nU,rU,iU,aU,oU,sU,cU,lU=Z(()=>{RH(),YH=typeof location>`u`?void 0:location.origin,XH=import.meta.url>`file:`&&import.meta.url<`file;`,ZH=()=>XH?new URL(new URL(`ort.bundle.min.mjs`,import.meta.url).href,YH).href:import.meta.url,QH=ZH(),$H=()=>{if(QH&&!QH.startsWith(`blob:`))return QH.substring(0,QH.lastIndexOf(`/`)+1)},eU=(e,t)=>{try{let n=t??QH;return(n?new URL(e,n):new URL(e)).origin===YH}catch{return!1}},tU=(e,t)=>{let n=t??QH;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},nU=(e,t)=>`${t??`./`}${e}`,rU=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},iU=async e=>(await i(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,aU=(UH(),zV(zH)).default,oU=async()=>{if(!QH)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(eU(QH))return[void 0,aU()];let e=await rU(QH);return[e,aU(e)]},sU=(JH(),zV(WH)).default,cU=async(e,t,n,r)=>{let i=sU&&!(e||t);if(i)if(QH)i=eU(QH)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,sU];{let r=`ort-wasm-simd-threaded.jsep.mjs`,i=e??tU(r,t),a=n&&i&&!eU(i,t),o=a?await rU(i):i??nU(r,t);return[a?o:void 0,await iU(o)]}}}),uU,dU,fU,pU,mU,hU,gU,_U,vU,yU=Z(()=>{lU(),dU=!1,fU=!1,pU=!1,mU=()=>{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}},hU=()=>{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}},gU=()=>{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}},_U=async e=>{if(dU)return Promise.resolve();if(fU)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(pU)throw Error(`previous call to 'initializeWebAssembly()' failed.`);fU=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!gU())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!hU())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=mU();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 cU(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=$H();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{fU=!1,dU=!0,uU=t,e(),d&&URL.revokeObjectURL(d)},e=>{fU=!1,pU=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},vU=()=>{if(dU&&uU)return uU;throw Error(`WebAssembly is not initialized yet.`)}}),bU,xU,SU,CU=Z(()=>{yU(),bU=(e,t)=>{let n=vU(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},xU=(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`)xU(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}`)})},SU=e=>{let t=vU(),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)}}}),wU,TU=Z(()=>{yU(),CU(),wU=e=>{let t=vU(),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=bU(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&SU(`Can't create run options.`),e?.extra!==void 0&&xU(e.extra,``,new WeakSet,(e,i)=>{let a=bU(e,r),o=bU(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&SU(`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}}}),EU,DU,OU,kU,AU,jU,MU=Z(()=>{yU(),CU(),EU=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}`)}},DU=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},OU=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)},kU=(e,t,n,r)=>{let i=bU(t,r),a=bU(n,r);vU()._OrtAddSessionConfigEntry(e,i,a)!==0&&SU(`Can't set a session config entry: ${t} - ${n}.`)},AU=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,typeof t!=`string`){let r=t?.deviceType;r&&kU(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);kU(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=bU(r,n),o=i.length,s=0,c=0;if(o>0){s=vU()._malloc(o*vU().PTR_SIZE),n.push(s),c=vU()._malloc(o*vU().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)vU().setValue(s+e*vU().PTR_SIZE,i[e][0],`*`),vU().setValue(c+e*vU().PTR_SIZE,i[e][1],`*`)}await vU()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&SU(`Can't append execution provider: ${r}.`)}},jU=async e=>{let t=vU(),n=0,r=[],i=e||{};OU(i);try{let e=EU(i.graphOptimizationLevel??`all`),a=DU(i.executionMode??`sequential`),o=typeof i.logId==`string`?bU(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`?bU(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&SU(`Can't create session options.`),i.executionProviders&&await AU(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);kU(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=bU(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&SU(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&xU(i.extra,``,new WeakSet,(e,t)=>{kU(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&SU(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),NU,PU,FU,IU,LU,RU,zU,BU,VU=Z(()=>{NU=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}`)}},PU=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}`)}},FU=(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},IU=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}`)}},LU=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}`)}},RU=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,zU=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,BU=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}`)}}}),HU,UU=Z(()=>{RH(),HU=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)}}),WU,GU,KU,qU,JU,YU,XU,ZU=Z(()=>{VU(),WU=[`V`,`I`,`W`,`E`,`F`],GU=(e,t)=>{console.log(`[${WU[e]},${new Date().toISOString()}]${t}`)},JU=(e,t)=>{KU=e,qU=t},YU=(e,t)=>{let n=LU(e);n>=LU(KU)&&GU(n,typeof t==`function`?t():t)},XU=(...e)=>{qU&&YU(...e)}}),QU,$U,Q,eW,tW,nW,rW,iW=Z(()=>{QU=class{static calcMatMulShape(e,t){return e[1]===t[0]?[e[0],t[1]]:void 0}},$U=class{static calcShape(e,t,n=!1){let r=e.length,i=t.length;if(r===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),o=Array(a);if(n){if(r<2||i<2)return;let n=QU.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(n===void 0)return;[o[a-2],o[a-1]]=n}for(let s=n?3:1;s<=a;s++){let n=r-s<0?1:e[r-s],c=i-s<0?1:t[i-s];if(n!==c&&n>1&&c>1)return;let l=Math.max(n,c);if(n&&c)o[a-s]=Math.max(n,c);else{if(l>1)return;o[a-s]=0}}return o}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(e[n-i]!==1&&e[n-i]!==t[r-i])return!1;return!0}},Q=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(n===0)return[];let r=Array(n),i=n-1;for(;i>=0;){if(e[i]%t===0){r[i]=e[i]/t;break}if(t%e[i]!==0)throw Error(`cannot convert shape`);r[i]=1,t/=e[i],i--}for(i--;i>=0;i--)r[i]=e[i];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<0)throw Error(`cannot get valid size from specified dimension range. Most likely the range contains negative values in them.`);r*=Number(e[i])}return r}static computeStrides(e){let t=e.length;if(t===0)return[];if(t===1)return[1];let n=Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw Error(`unsupported axis for this operation.`);return e<0?e+t:e}static normalizeAxes(e,t){return e.map(n=>this.normalizeAxis(n,t??e.length))}static sortBasedOnPerm(e,t){return t?t.map(t=>e[t]):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map((e,r)=>e+t[r]+t[r+n])}static areEqual(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}},eW=class e{static adjustPoolAttributes(e,t,n,r,i,a){if(!e&&n.length!==t.length-2)throw Error(`length of specified kernel shapes should be 2 less than length of input dimensions`);if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw Error(`strides should be greater than or equal to 1`)}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw Error(`dilations should be greater than or equal to 1`)}else i.push(1);for(let e=0;e<n.length*2;e++)if(e<a.length){if(a[e]<0)throw Error(`pad should be greater than or equal to 1`)}else a.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw Error(`kernel shapes need to be greater than 0`);if(a[e]>=n[e]||a[e+n.length]>=n[e])throw Error(`pads should be smaller than kernel`)}}static adjustPadsBasedOnAutoPad(t,n,r,i,a,o,s){if(s){if(a.length!==2*(t.length-2))throw Error(`length of pads should be twice the length of data dimensions`);if(n.length!==t.length-2)throw Error(`length of strides should be the length of data dimensions`);if(i.length!==t.length-2)throw Error(`length of kernel shapes should be the length of data dimensions`);for(let c=0;c<t.length-2;c++)e.adjustPadAndReturnShape(t[c+(o?1:2)],n[c],r[c],i[c],a,c,c+t.length-2,s)}}static computePoolOutputShape(t,n,r,i,a,o,s){if(n.length<=0)throw Error(`input shape must be of size greater than 0`);let c=[n[0],n[1]];return e.computeShapeHelper(t,n,c,r,i,a,o,s),c}static computeConvOutputShape(t,n,r,i,a,o,s){if(t.length<=0||n.length<=0)throw Error(`invalid input tensor dims or invalid filter tensor dims`);let c=[t[0],n[0]];return e.computeShapeHelper(!1,t,c,r,i,a,o,s),c}static computeShapeHelper(t,n,r,i,a,o,s,c){if(t)for(let e=0;e<n.length-2;e++)r.push(1);else for(let t=0;t<n.length-2;t++)r.push(e.adjustPadAndReturnShape(n[t+2],i[t],a[t],o[t],s,t,t+n.length-2,c))}static adjustPadAndReturnShape(e,t,n,r,i,a,o,s){let c=n*(r-1)+1;if(s&&s!==`NOTSET`)switch(s){case`VALID`:return i[a]=0,i[o]=0,Math.floor((e-c)/t+1);case`SAME_LOWER`:case`SAME_UPPER`:if(n!==1)throw Error(`Dilation not supported for SAME_UPPER or SAME_LOWER`);{let n=((e+t-1)/t-1)*t+r-e;return i[a]=Math.floor(s===`SAME_LOWER`?(n+1)/2:n/2),i[o]=n-i[a],Math.floor((e+n-r)/t+1)}default:throw Error(`Unsupported AutoPad type`)}else return Math.floor((e+i[a]+i[o]-c)/t+1)}},tW=class{static getShapeOfGemmResult(e,t,n,r,i){if(e.length!==2||n.length!==2)throw Error(`shape need to be of size 2`);let a,o,s;t?(a=e[1],o=e[0]):(a=e[0],o=e[1]);let c=-1;if(r?(s=n[0],c=1):(s=n[1],c=0),n[c]!==o)throw Error(`dimension mismatch`);if(a<=0||s<=0||o<=0)throw Error(`invalid shape specified`);if(i&&!$U.isValidBroadcast(i,[a,s]))throw Error(`gemm: invalid bias shape for broadcast`);return[a,s,o]}},nW=-34028234663852886e22,rW=34028234663852886e22}),aW,oW=Z(()=>{VU(),aW=(e,t)=>new(IU(t))(e)}),sW,cW,lW,uW,dW,fW,pW,mW,hW,gW,_W,vW=Z(()=>{VU(),ZU(),sW=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),cW=(e,t)=>{if(t===`int32`)return e;let n=sW.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(IU(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||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'`)}},lW=(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}`)}},uW=1,dW=()=>uW++,fW=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),pW=(e,t)=>{let n=sW.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},mW=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 pW(this.dataType,this.tensorShape)}destroy(){XU(`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=lW(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}},hW=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=fW.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);XU(`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!==pW(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=cW(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 XU(`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?lW(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()}},gW=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=dW();return this.tensorTrackersById.set(e,new hW(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){XU(`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){XU(`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=dW(),o=new mW({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new hW(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)){XU(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}XU(`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 mW({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)}},_W=(...e)=>new gW(...e)}),yW,bW,xW,SW=Z(()=>{VU(),yU(),oW(),vW(),ZU(),yW=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),bW=(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])},xW=class{constructor(e){this.tensorManager=_W(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,JU(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){XU(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){XU(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)XU(`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=>bW(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){XU(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=yW.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){XU(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=yW.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(!vU().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);XU(`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 aW(n,t)}}registerMLTensor(e,t,n,r){let i=yW.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return XU(`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=cW(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 XU(`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=yW.get(NU(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),CW=Z(()=>{}),wW,TW,EW,DW,OW,kW,AW,jW,MW,NW=Z(()=>{ZU(),CW(),wW=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),TW=[],EW=e=>Math.ceil(Number(e)/16)*16,DW=e=>{for(let t=0;t<TW.length;t++){let n=TW[t];if(e<=n)return n}return Math.ceil(e/16)*16},OW=1,kW=()=>OW++,AW=async(e,t,n,r)=>{let i=EW(n),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let s=a.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(s,0,n)),e}else return new Uint8Array(s.slice(0,n))}finally{a.destroy()}},jW=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[e]of wW)TW.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,r=t.byteOffset,i=t.byteLength,a=EW(i),o=this.storageCache.get(e);if(!o)throw Error(`gpu data for uploading does not exist`);if(Number(o.originalSize)!==i)throw Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let s=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=s.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,r,i)),s.unmap();let l=this.backend.device.createCommandEncoder();l.copyBufferToBuffer(s,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([l.finish()]),s.destroy(),XU(`verbose`,()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw Error(`source gpu data for memcpy does not exist`);let r=this.storageCache.get(t);if(!r)throw Error(`destination gpu data for memcpy does not exist`);if(n.originalSize!==r.originalSize)throw Error(`inconsistent source and destination gpu data size`);let i=EW(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(e,t,n){let r;if(n){if(r=n[0],e===n[1])return XU(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw Error(`Registering a different external buffer under graph capture mode is not supported yet.
12832
- Please use the previous external buffer!`)}else r=kW();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),XU(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`),r}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),XU(`verbose`,()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=DW(e),r,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let e=(i?this.freeBuffers:this.freeUniformBuffers).get(n);r=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:n,usage:t})}else r=this.backend.device.createBuffer({size:n,usage:t});let o={id:kW(),type:0,buffer:r};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),XU(`verbose`,()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e==`bigint`?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw Error(`releasing data does not exist`)}return XU(`verbose`,()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw Error(`data does not exist`);await AW(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=wW.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(e=>{e.destroy()}),this.capturedPendingBuffers.delete(e)),--this.sessionCount,this.sessionCount===0&&(XU(`warning`,()=>`[WebGPU] Clearing webgpu buffer cache`),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.storageCache=new Map)}},MW=(...e)=>new jW(...e)}),PW,FW,IW=Z(()=>{PW=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(`;`),this.key}},FW=e=>new PW(e)}),LW,RW,zW,BW,VW,HW,UW,WW,GW,KW,qW,$,JW,YW,XW,ZW,QW,$W=Z(()=>{VU(),iW(),LW=64,RW=(e,t)=>{if(t===3)throw Error(`vec3 has same alignment as vec4, use vec4 instead`);switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:`f16`;case 1:return t>1?`vec${t}<f32>`:`f32`;case 6:return t>1?`vec${t}<i32>`:`i32`;case 12:return t>1?`vec${t}<u32>`:`u32`;case 7:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`i32`];case 13:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`u32`];case 9:if(t!==4)throw Error(`bool must be vec4`);return[`u32`,`vec4<bool>`];case 22:return`i32`;case 21:return`u32`;default:throw Error(`Unknown data type: ${e}`)}},zW=(e,t=1)=>{let n=RW(e,t);return typeof n==`string`?n:n[0]},BW=(e,t=1)=>{let n=RW(e,t);return typeof n==`string`?n:n[1]},VW=(...e)=>{let t=[];return e.forEach(e=>{e.length!==0&&t.push({type:12,data:e},{type:12,data:Q.computeStrides(e)})}),t},HW=e=>e%4==0?4:e%2==0?2:1,UW=(e=`f32`,t,n=`0`)=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,WW=(e,t,n)=>e===`f32`?n:t===1?`f32(${n})`:`vec${t}<f32>(${n})`,GW=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,KW=(e,t,n,r)=>e.startsWith(`uniforms.`)&&n>4?typeof t==`string`?r===`f16`?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:r===`f16`?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,qW=(e,t,n,r,i)=>{let a=typeof n==`number`,o=a?n:n.length,s=[...Array(o).keys()],c=o<2?`u32`:o<=4?`vec${o}<u32>`:`array<u32, ${o}>`,l=RW(t,i),u=typeof l==`string`?l:l[1],d={indices:c,value:u,storage:typeof l==`string`?l:l[0],tensor:t},f=e=>typeof e==`string`?e:`${e}u`,p={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},m=a?`uniforms.`:``,h=`${m}${e}_shape`,g=`${m}${e}_strides`,_=``;for(let e=0;e<o-1;e++)_+=`
12833
- let dim${e} = current / ${KW(g,e,o)};
12834
- let rest${e} = current % ${KW(g,e,o)};
12831
+ `))[0]==`Error`&&r.shift(),Zn(r);for(var i=3;r[i]&&Xn(r[i])!=e;)++i;for(e=0;e<n&&r[e+i];++e)(w(),A)[t+4*e>>>2>>>0]=Xn(r[e+i]);return e}var nr,rr={},ir=()=>{if(!nr){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]}`);nr=n}return nr};function ar(e,t){if(i)return H(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of ir()){var o=t+r;(w(),j)[e+a>>>2>>>0]=o,r+=xt(n,o,1/0)+1,a+=4}return 0}function or(e,t){if(i)return H(20,1,e,t);e>>>=0,t>>>=0;var n=ir();for(var r of((w(),j)[e>>>2>>>0]=n.length,e=0,n))e+=St(r)+1;return(w(),j)[t>>>2>>>0]=e,0}function sr(e){return i?H(21,1,e):52}function cr(e,t,n,r){return i?H(22,1,e,t,n,r):52}function lr(e,t,n,r){return i?H(23,1,e,t,n,r):70}var ur=[null,[],[]];function dr(e,t,n,r){if(i)return H(24,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o<n;o++){var s=(w(),j)[t>>>2>>>0],c=(w(),j)[t+4>>>2>>>0];t+=8;for(var l=0;l<c;l++){var u=e,d=(w(),D)[s+l>>>0],f=ur[u];d===0||d===10?((u===1?b:x)(W(f)),f.length=0):f.push(d)}a+=c}return(w(),j)[r>>>2>>>0]=a,0}function fr(e){return e>>>0}i||function(){for(var e=t.numThreads-1;e--;)_e();re.push(async()=>{var e=async function(){if(!i)return Promise.all(U.map(ge))}();ie++,await e,--ie==0&&ae&&(e=ae,ae=null,e())})}(),i||(ve=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),R()),t.wasmBinary&&(f=t.wasmBinary),t.stackSave=()=>Ar(),t.stackRestore=e=>Or(e),t.stackAlloc=e=>kr(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(w(),E)[e>>>0]=t;break;case`i16`:(w(),O)[e>>>1>>>0]=t;break;case`i32`:(w(),A)[e>>>2>>>0]=t;break;case`i64`:(w(),P)[e>>>3>>>0]=BigInt(t);break;case`float`:(w(),M)[e>>>2>>>0]=t;break;case`double`:(w(),N)[e>>>3>>>0]=t;break;case`*`:(w(),j)[e>>>2>>>0]=t;break;default:B(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(w(),E)[e>>>0];case`i16`:return(w(),O)[e>>>1>>>0];case`i32`:return(w(),A)[e>>>2>>>0];case`i64`:return(w(),P)[e>>>3>>>0];case`float`:return(w(),M)[e>>>2>>>0];case`double`:return(w(),N)[e>>>3>>>0];case`*`:return(w(),j)[e>>>2>>>0];default:B(`invalid type for getValue: ${t}`)}},t.UTF8ToString=Be,t.stringToUTF8=xt,t.lengthBytesUTF8=St;var pr,mr,hr,gr,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,K,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,q,hi,gi,_i,vi,yi,bi,xi,Si=[ce,le,Fe,Ve,He,Ue,We,G,Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,jn,Mn,Fn,ar,or,sr,cr,lr,dr],Ci={929356:(e,n,r,i,a)=>{if(t===void 0||!t.Zc)return 1;if((e=Be(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.Zc.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:(w(),D).set(o,i>>>0);break;case 1:t.Xd?t.Xd(i,o):t.Ld(i,o);break;default:return 4}return 0}catch{return 4}},930180:(e,n,r)=>{t.xd(e,(w(),D).subarray(n>>>0,n+r>>>0))},930244:()=>t.Zd(),930286:e=>{t.vd(e)},930323:()=>{t.Ed()},930354:()=>{t.Fd()},930383:()=>{t.Jd()},930408:e=>t.Dd(e),930441:e=>t.Hd(e),930473:(e,n,r)=>{t.jd(Number(e),Number(n),Number(r),!0)},930536:(e,n,r)=>{t.jd(Number(e),Number(n),Number(r))},930593:()=>typeof wasmOffsetConverter<`u`,930650:e=>{t.ac(`Abs`,e,void 0)},930701:e=>{t.ac(`Neg`,e,void 0)},930752:e=>{t.ac(`Floor`,e,void 0)},930805:e=>{t.ac(`Ceil`,e,void 0)},930857:e=>{t.ac(`Reciprocal`,e,void 0)},930915:e=>{t.ac(`Sqrt`,e,void 0)},930967:e=>{t.ac(`Exp`,e,void 0)},931018:e=>{t.ac(`Erf`,e,void 0)},931069:e=>{t.ac(`Sigmoid`,e,void 0)},931124:(e,n,r)=>{t.ac(`HardSigmoid`,e,{alpha:n,beta:r})},931203:e=>{t.ac(`Log`,e,void 0)},931254:e=>{t.ac(`Sin`,e,void 0)},931305:e=>{t.ac(`Cos`,e,void 0)},931356:e=>{t.ac(`Tan`,e,void 0)},931407:e=>{t.ac(`Asin`,e,void 0)},931459:e=>{t.ac(`Acos`,e,void 0)},931511:e=>{t.ac(`Atan`,e,void 0)},931563:e=>{t.ac(`Sinh`,e,void 0)},931615:e=>{t.ac(`Cosh`,e,void 0)},931667:e=>{t.ac(`Asinh`,e,void 0)},931720:e=>{t.ac(`Acosh`,e,void 0)},931773:e=>{t.ac(`Atanh`,e,void 0)},931826:e=>{t.ac(`Tanh`,e,void 0)},931878:e=>{t.ac(`Not`,e,void 0)},931929:(e,n,r)=>{t.ac(`Clip`,e,{min:n,max:r})},931998:e=>{t.ac(`Clip`,e,void 0)},932050:(e,n)=>{t.ac(`Elu`,e,{alpha:n})},932108:e=>{t.ac(`Gelu`,e,void 0)},932160:e=>{t.ac(`Relu`,e,void 0)},932212:(e,n)=>{t.ac(`LeakyRelu`,e,{alpha:n})},932276:(e,n)=>{t.ac(`ThresholdedRelu`,e,{alpha:n})},932346:(e,n)=>{t.ac(`Cast`,e,{to:n})},932404:e=>{t.ac(`Add`,e,void 0)},932455:e=>{t.ac(`Sub`,e,void 0)},932506:e=>{t.ac(`Mul`,e,void 0)},932557:e=>{t.ac(`Div`,e,void 0)},932608:e=>{t.ac(`Pow`,e,void 0)},932659:e=>{t.ac(`Equal`,e,void 0)},932712:e=>{t.ac(`Greater`,e,void 0)},932767:e=>{t.ac(`GreaterOrEqual`,e,void 0)},932829:e=>{t.ac(`Less`,e,void 0)},932881:e=>{t.ac(`LessOrEqual`,e,void 0)},932940:(e,n,r,i,a)=>{t.ac(`ReduceMean`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933115:(e,n,r,i,a)=>{t.ac(`ReduceMax`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933289:(e,n,r,i,a)=>{t.ac(`ReduceMin`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933463:(e,n,r,i,a)=>{t.ac(`ReduceProd`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933638:(e,n,r,i,a)=>{t.ac(`ReduceSum`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933812:(e,n,r,i,a)=>{t.ac(`ReduceL1`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},933985:(e,n,r,i,a)=>{t.ac(`ReduceL2`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934158:(e,n,r,i,a)=>{t.ac(`ReduceLogSum`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934335:(e,n,r,i,a)=>{t.ac(`ReduceSumSquare`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934515:(e,n,r,i,a)=>{t.ac(`ReduceLogSumExp`,e,{keepDims:!!n,noopWithEmptyAxes:!!r,axes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},934695:e=>{t.ac(`Where`,e,void 0)},934748:(e,n,r)=>{t.ac(`Transpose`,e,{perm:n?Array.from((w(),A).subarray(Number(n)>>>0,Number(r)>>>0)):[]})},934872:(e,n,r,i)=>{t.ac(`DepthToSpace`,e,{blocksize:n,mode:Be(r),format:i?`NHWC`:`NCHW`})},935005:(e,n,r,i)=>{t.ac(`DepthToSpace`,e,{blocksize:n,mode:Be(r),format:i?`NHWC`:`NCHW`})},935138:(e,n,r,i,a,o,s,c,l,u,d,f,p,m,h)=>{t.ac(`ConvTranspose`,e,{format:l?`NHWC`:`NCHW`,autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,s],strides:[c],wIsConst:()=>!!(w(),E)[u>>>0],outputPadding:d?Array.from((w(),A).subarray(Number(d)>>>0,Number(f)>>>0)):[],outputShape:p?Array.from((w(),A).subarray(Number(p)>>>0,Number(m)>>>0)):[],activation:Be(h)})},935571:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`ConvTranspose`,e,{format:c?`NHWC`:`NCHW`,autoPad:n,dilations:Array.from((w(),A).subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from((w(),A).subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from((w(),A).subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from((w(),A).subarray(Number(s)>>>0,2+(Number(s)>>>0)>>>0)),wIsConst:()=>!!(w(),E)[l>>>0],outputPadding:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],outputShape:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[],activation:Be(m)})},936232:(e,n,r,i,a,o,s,c,l,u,d,f,p,m,h)=>{t.ac(`ConvTranspose`,e,{format:l?`NHWC`:`NCHW`,autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,s],strides:[c],wIsConst:()=>!!(w(),E)[u>>>0],outputPadding:d?Array.from((w(),A).subarray(Number(d)>>>0,Number(f)>>>0)):[],outputShape:p?Array.from((w(),A).subarray(Number(p)>>>0,Number(m)>>>0)):[],activation:Be(h)})},936665:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`ConvTranspose`,e,{format:c?`NHWC`:`NCHW`,autoPad:n,dilations:Array.from((w(),A).subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from((w(),A).subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from((w(),A).subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from((w(),A).subarray(Number(s)>>>0,2+(Number(s)>>>0)>>>0)),wIsConst:()=>!!(w(),E)[l>>>0],outputPadding:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],outputShape:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[],activation:Be(m)})},937326:(e,n)=>{t.ac(`GlobalAveragePool`,e,{format:n?`NHWC`:`NCHW`})},937417:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`AveragePool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},937896:(e,n)=>{t.ac(`GlobalAveragePool`,e,{format:n?`NHWC`:`NCHW`})},937987:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`AveragePool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},938466:(e,n)=>{t.ac(`GlobalMaxPool`,e,{format:n?`NHWC`:`NCHW`})},938553:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`MaxPool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},939028:(e,n)=>{t.ac(`GlobalMaxPool`,e,{format:n?`NHWC`:`NCHW`})},939115:(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{t.ac(`MaxPool`,e,{format:m?`NHWC`:`NCHW`,auto_pad:n,ceil_mode:r,count_include_pad:i,storage_order:a,dilations:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],kernel_shape:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],pads:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],strides:f?Array.from((w(),A).subarray(Number(f)>>>0,Number(p)>>>0)):[]})},939590:(e,n,r,i,a)=>{t.ac(`Gemm`,e,{alpha:n,beta:r,transA:i,transB:a})},939694:e=>{t.ac(`MatMul`,e,void 0)},939748:(e,n,r,i)=>{t.ac(`ArgMax`,e,{keepDims:!!n,selectLastIndex:!!r,axis:i})},939856:(e,n,r,i)=>{t.ac(`ArgMin`,e,{keepDims:!!n,selectLastIndex:!!r,axis:i})},939964:(e,n)=>{t.ac(`Softmax`,e,{axis:n})},940027:(e,n)=>{t.ac(`Concat`,e,{axis:n})},940087:(e,n,r,i,a)=>{t.ac(`Split`,e,{axis:n,numOutputs:r,splitSizes:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},940243:e=>{t.ac(`Expand`,e,void 0)},940297:(e,n)=>{t.ac(`Gather`,e,{axis:Number(n)})},940368:(e,n)=>{t.ac(`GatherElements`,e,{axis:Number(n)})},940447:(e,n)=>{t.ac(`GatherND`,e,{batch_dims:Number(n)})},940526:(e,n,r,i,a,o,s,c,l,u,d)=>{t.ac(`Resize`,e,{antialias:n,axes:r?Array.from((w(),A).subarray(Number(r)>>>0,Number(i)>>>0)):[],coordinateTransformMode:Be(a),cubicCoeffA:o,excludeOutside:s,extrapolationValue:c,keepAspectRatioPolicy:Be(l),mode:Be(u),nearestMode:Be(d)})},940888:(e,n,r,i,a,o,s)=>{t.ac(`Slice`,e,{starts:n?Array.from((w(),A).subarray(Number(n)>>>0,Number(r)>>>0)):[],ends:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[],axes:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[]})},941152:e=>{t.ac(`Tile`,e,void 0)},941204:(e,n,r)=>{t.ac(`InstanceNormalization`,e,{epsilon:n,format:r?`NHWC`:`NCHW`})},941318:(e,n,r)=>{t.ac(`InstanceNormalization`,e,{epsilon:n,format:r?`NHWC`:`NCHW`})},941432:e=>{t.ac(`Range`,e,void 0)},941485:(e,n)=>{t.ac(`Einsum`,e,{equation:Be(n)})},941566:(e,n,r,i,a)=>{t.ac(`Pad`,e,{mode:n,value:r,pads:i?Array.from((w(),A).subarray(Number(i)>>>0,Number(a)>>>0)):[]})},941709:(e,n,r,i,a,o)=>{t.ac(`BatchNormalization`,e,{epsilon:n,momentum:r,spatial:!!a,trainingMode:!!i,format:o?`NHWC`:`NCHW`})},941878:(e,n,r,i,a,o)=>{t.ac(`BatchNormalization`,e,{epsilon:n,momentum:r,spatial:!!a,trainingMode:!!i,format:o?`NHWC`:`NCHW`})},942047:(e,n,r)=>{t.ac(`CumSum`,e,{exclusive:Number(n),reverse:Number(r)})},942144:(e,n,r)=>{t.ac(`DequantizeLinear`,e,{axis:n,blockSize:r})},942234:(e,n,r,i,a)=>{t.ac(`GridSample`,e,{align_corners:n,mode:Be(r),padding_mode:Be(i),format:a?`NHWC`:`NCHW`})},942404:(e,n,r,i,a)=>{t.ac(`GridSample`,e,{align_corners:n,mode:Be(r),padding_mode:Be(i),format:a?`NHWC`:`NCHW`})},942574:(e,n)=>{t.ac(`ScatterND`,e,{reduction:Be(n)})},942659:(e,n,r,i,a,o,s,c,l)=>{t.ac(`Attention`,e,{numHeads:n,isUnidirectional:r,maskFilterValue:i,scale:a,doRotary:o,qkvHiddenSizes:s?Array.from((w(),A).subarray(Number(c)>>>0,Number(c)+s>>>0)):[],pastPresentShareBuffer:!!l})},942931:e=>{t.ac(`BiasAdd`,e,void 0)},942986:e=>{t.ac(`BiasSplitGelu`,e,void 0)},943047:e=>{t.ac(`FastGelu`,e,void 0)},943103:(e,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g)=>{t.ac(`Conv`,e,{format:f?`NHWC`:`NCHW`,auto_pad:n,dilations:r?Array.from((w(),A).subarray(Number(r)>>>0,Number(i)>>>0)):[],group:a,kernel_shape:o?Array.from((w(),A).subarray(Number(o)>>>0,Number(s)>>>0)):[],pads:c?Array.from((w(),A).subarray(Number(c)>>>0,Number(l)>>>0)):[],strides:u?Array.from((w(),A).subarray(Number(u)>>>0,Number(d)>>>0)):[],w_is_const:()=>!!(w(),E)[Number(p)>>>0],activation:Be(m),activation_params:h?Array.from((w(),M).subarray(Number(h)>>>0,Number(g)>>>0)):[]})},943687:e=>{t.ac(`Gelu`,e,void 0)},943739:(e,n,r,i,a,o,s,c,l)=>{t.ac(`GroupQueryAttention`,e,{numHeads:n,kvNumHeads:r,scale:i,softcap:a,doRotary:o,rotaryInterleaved:s,smoothSoftmax:c,localWindowSize:l})},943956:(e,n,r,i)=>{t.ac(`LayerNormalization`,e,{axis:n,epsilon:r,simplified:!!i})},944067:(e,n,r,i)=>{t.ac(`LayerNormalization`,e,{axis:n,epsilon:r,simplified:!!i})},944178:(e,n,r,i,a,o)=>{t.ac(`MatMulNBits`,e,{k:n,n:r,accuracyLevel:i,bits:a,blockSize:o})},944305:(e,n,r,i,a,o)=>{t.ac(`MultiHeadAttention`,e,{numHeads:n,isUnidirectional:r,maskFilterValue:i,scale:a,doRotary:o})},944464:(e,n)=>{t.ac(`QuickGelu`,e,{alpha:n})},944528:(e,n,r,i,a)=>{t.ac(`RotaryEmbedding`,e,{interleaved:!!n,numHeads:r,rotaryEmbeddingDim:i,scale:a})},944667:(e,n,r)=>{t.ac(`SkipLayerNormalization`,e,{epsilon:n,simplified:!!r})},944769:(e,n,r)=>{t.ac(`SkipLayerNormalization`,e,{epsilon:n,simplified:!!r})},944871:(e,n,r,i)=>{t.ac(`GatherBlockQuantized`,e,{gatherAxis:n,quantizeAxis:r,blockSize:i})},944992:e=>{t.Id(e)},945026:(e,n)=>t.Kd(Number(e),Number(n),t.$c.Nd,t.$c.errors)};function wi(e,n,r){return nn(async()=>{await t.Gd(Number(e),Number(n),Number(r))})}function Ti(){return typeof wasmOffsetConverter<`u`}function Ei(e,t,n,r){var i=Ar();try{return Ur(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function Di(e,t,n){var r=Ar();try{return zr(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function Oi(e,t,n){var r=Ar();try{Pr(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function ki(e,t){var n=Ar();try{return Fr(e,t)}catch(e){if(Or(n),e!==e+0)throw e;Tr(1,0)}}function Ai(e){var t=Ar();try{Ir(e)}catch(e){if(Or(t),e!==e+0)throw e;Tr(1,0)}}function ji(e,t,n,r,i,a,o){var s=Ar();try{return Vr(e,t,n,r,i,a,o)}catch(e){if(Or(s),e!==e+0)throw e;Tr(1,0)}}function Mi(e,t){var n=Ar();try{Wr(e,t)}catch(e){if(Or(n),e!==e+0)throw e;Tr(1,0)}}function Ni(e,t,n,r,i,a){var o=Ar();try{Lr(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Pi(e,t,n,r){var i=Ar();try{Hr(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function Fi(e,t,n,r,i){var a=Ar();try{Rr(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function Ii(e,t,n,r,i,a,o){var s=Ar();try{Kr(e,t,n,r,i,a,o)}catch(e){if(Or(s),e!==e+0)throw e;Tr(1,0)}}function Li(e,t,n,r,i,a,o){var s=Ar();try{qr(e,t,n,r,i,a,o)}catch(e){if(Or(s),e!==e+0)throw e;Tr(1,0)}}function Ri(e,t,n,r,i,a,o,s){var c=Ar();try{Zr(e,t,n,r,i,a,o,s)}catch(e){if(Or(c),e!==e+0)throw e;Tr(1,0)}}function zi(e,t,n,r,i){var a=Ar();try{return Gr(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function Bi(e,t,n,r,i,a,o,s){var c=Ar();try{Qr(e,t,n,r,i,a,o,s)}catch(e){if(Or(c),e!==e+0)throw e;Tr(1,0)}}function Vi(e,t,n,r,i,a,o,s,c,l,u,d){var f=Ar();try{Jr(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(Or(f),e!==e+0)throw e;Tr(1,0)}}function Hi(e,t,n,r,i,a){var o=Ar();try{return Yr(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Ui(e,t,n){var r=Ar();try{return $r(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;return Tr(1,0),0n}}function Wi(e,t,n,r,i,a,o,s,c){var l=Ar();try{Br(e,t,n,r,i,a,o,s,c)}catch(e){if(Or(l),e!==e+0)throw e;Tr(1,0)}}function Gi(e){var t=Ar();try{return ei(e)}catch(e){if(Or(t),e!==e+0)throw e;Tr(1,0)}}function Ki(e,t,n){var r=Ar();try{return ti(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function qi(e,t){var n=Ar();try{return gi(e,t)}catch(e){if(Or(n),e!==e+0)throw e;return Tr(1,0),0n}}function Ji(e,t,n,r,i){var a=Ar();try{ni(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function Yi(e){var t=Ar();try{return ri(e)}catch(e){if(Or(t),e!==e+0)throw e;return Tr(1,0),0n}}function Xi(e,t,n,r,i,a){var o=Ar();try{return li(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Zi(e,t,n,r,i,a){var o=Ar();try{return ui(e,t,n,r,i,a)}catch(e){if(Or(o),e!==e+0)throw e;Tr(1,0)}}function Qi(e,t,n,r,i,a,o,s){var c=Ar();try{return Xr(e,t,n,r,i,a,o,s)}catch(e){if(Or(c),e!==e+0)throw e;Tr(1,0)}}function $i(e,t,n,r,i){var a=Ar();try{return di(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;return Tr(1,0),0n}}function ea(e,t,n,r){var i=Ar();try{return fi(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function ta(e,t,n,r){var i=Ar();try{return pi(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function na(e,t,n,r,i,a,o,s,c,l,u,d){var f=Ar();try{return mi(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(Or(f),e!==e+0)throw e;Tr(1,0)}}function ra(e,t,n,r,i,a,o,s,c,l,u){var d=Ar();try{si(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(Or(d),e!==e+0)throw e;Tr(1,0)}}function ia(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=Ar();try{ci(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(Or(g),e!==e+0)throw e;Tr(1,0)}}function aa(e,t,n,r){var i=Ar();try{return q(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function oa(e,t,n,r,i){var a=Ar();try{return hi(e,t,n,r,i)}catch(e){if(Or(a),e!==e+0)throw e;Tr(1,0)}}function sa(e,t,n){var r=Ar();try{return ii(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function ca(e,t,n){var r=Ar();try{return ai(e,t,n)}catch(e){if(Or(r),e!==e+0)throw e;Tr(1,0)}}function la(e,t,n,r){var i=Ar();try{oi(e,t,n,r)}catch(e){if(Or(i),e!==e+0)throw e;Tr(1,0)}}function ua(){if(0<ie)ae=ua;else if(i)h?.(t),z();else{for(var e=re;0<e.length;)e.shift()(t);0<ie?ae=ua:(t.calledRun=!0,S||(z(),h?.(t)))}}return i||(xi=await ee(),ua()),t.PTR_SIZE=4,L?t:new Promise((e,t)=>{h=e,g=t})}var JH,YH,XH=Z(()=>{JH=qH,YH=globalThis.self?.name?.startsWith(`em-pthread`),YH&&qH()}),ZH,QH,$H,eU,tU,nU,rU,iU,aU,oU,sU,cU,lU,uU,dU=Z(()=>{BH(),ZH=typeof location>`u`?void 0:location.origin,QH=import.meta.url>`file:`&&import.meta.url<`file;`,$H=()=>QH?new URL(new URL(`ort.bundle.min.mjs`,import.meta.url).href,ZH).href:import.meta.url,eU=$H(),tU=()=>{if(eU&&!eU.startsWith(`blob:`))return eU.substring(0,eU.lastIndexOf(`/`)+1)},nU=(e,t)=>{try{let n=t??eU;return(n?new URL(e,n):new URL(e)).origin===ZH}catch{return!1}},rU=(e,t)=>{let n=t??eU;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},iU=(e,t)=>`${t??`./`}${e}`,aU=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},oU=async e=>(await i(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,sU=(GH(),VV(VH)).default,cU=async()=>{if(!eU)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(nU(eU))return[void 0,sU()];let e=await aU(eU);return[e,sU(e)]},lU=(XH(),VV(KH)).default,uU=async(e,t,n,r)=>{let i=lU&&!(e||t);if(i)if(eU)i=nU(eU)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,lU];{let r=`ort-wasm-simd-threaded.jsep.mjs`,i=e??rU(r,t),a=n&&i&&!nU(i,t),o=a?await aU(i):i??iU(r,t);return[a?o:void 0,await oU(o)]}}}),fU,pU,mU,hU,gU,_U,vU,yU,bU,xU=Z(()=>{dU(),pU=!1,mU=!1,hU=!1,gU=()=>{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}},_U=()=>{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}},vU=()=>{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}},yU=async e=>{if(pU)return Promise.resolve();if(mU)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(hU)throw Error(`previous call to 'initializeWebAssembly()' failed.`);mU=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!vU())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!_U())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=gU();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 uU(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=tU();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{mU=!1,pU=!0,fU=t,e(),d&&URL.revokeObjectURL(d)},e=>{mU=!1,hU=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},bU=()=>{if(pU&&fU)return fU;throw Error(`WebAssembly is not initialized yet.`)}}),SU,CU,wU,TU=Z(()=>{xU(),SU=(e,t)=>{let n=bU(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},CU=(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`)CU(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}`)})},wU=e=>{let t=bU(),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)}}}),EU,DU=Z(()=>{xU(),TU(),EU=e=>{let t=bU(),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=SU(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&wU(`Can't create run options.`),e?.extra!==void 0&&CU(e.extra,``,new WeakSet,(e,i)=>{let a=SU(e,r),o=SU(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&wU(`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}}}),OU,kU,AU,jU,MU,NU,PU=Z(()=>{xU(),TU(),OU=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}`)}},kU=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},AU=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)},jU=(e,t,n,r)=>{let i=SU(t,r),a=SU(n,r);bU()._OrtAddSessionConfigEntry(e,i,a)!==0&&wU(`Can't set a session config entry: ${t} - ${n}.`)},MU=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,typeof t!=`string`){let r=t?.deviceType;r&&jU(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);jU(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=SU(r,n),o=i.length,s=0,c=0;if(o>0){s=bU()._malloc(o*bU().PTR_SIZE),n.push(s),c=bU()._malloc(o*bU().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)bU().setValue(s+e*bU().PTR_SIZE,i[e][0],`*`),bU().setValue(c+e*bU().PTR_SIZE,i[e][1],`*`)}await bU()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&wU(`Can't append execution provider: ${r}.`)}},NU=async e=>{let t=bU(),n=0,r=[],i=e||{};AU(i);try{let e=OU(i.graphOptimizationLevel??`all`),a=kU(i.executionMode??`sequential`),o=typeof i.logId==`string`?SU(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`?SU(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&wU(`Can't create session options.`),i.executionProviders&&await MU(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);jU(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=SU(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&wU(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&CU(i.extra,``,new WeakSet,(e,t)=>{jU(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&wU(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),FU,IU,LU,RU,zU,BU,VU,HU,UU=Z(()=>{FU=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}`)}},IU=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}`)}},LU=(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},RU=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}`)}},zU=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}`)}},BU=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,VU=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,HU=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}`)}}}),WU,GU=Z(()=>{BH(),WU=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)}}),KU,qU,JU,YU,XU,ZU,QU,$U=Z(()=>{UU(),KU=[`V`,`I`,`W`,`E`,`F`],qU=(e,t)=>{console.log(`[${KU[e]},${new Date().toISOString()}]${t}`)},XU=(e,t)=>{JU=e,YU=t},ZU=(e,t)=>{let n=zU(e);n>=zU(JU)&&qU(n,typeof t==`function`?t():t)},QU=(...e)=>{YU&&ZU(...e)}}),eW,tW,Q,nW,rW,iW,aW,oW=Z(()=>{eW=class{static calcMatMulShape(e,t){return e[1]===t[0]?[e[0],t[1]]:void 0}},tW=class{static calcShape(e,t,n=!1){let r=e.length,i=t.length;if(r===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),o=Array(a);if(n){if(r<2||i<2)return;let n=eW.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(n===void 0)return;[o[a-2],o[a-1]]=n}for(let s=n?3:1;s<=a;s++){let n=r-s<0?1:e[r-s],c=i-s<0?1:t[i-s];if(n!==c&&n>1&&c>1)return;let l=Math.max(n,c);if(n&&c)o[a-s]=Math.max(n,c);else{if(l>1)return;o[a-s]=0}}return o}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(e[n-i]!==1&&e[n-i]!==t[r-i])return!1;return!0}},Q=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(n===0)return[];let r=Array(n),i=n-1;for(;i>=0;){if(e[i]%t===0){r[i]=e[i]/t;break}if(t%e[i]!==0)throw Error(`cannot convert shape`);r[i]=1,t/=e[i],i--}for(i--;i>=0;i--)r[i]=e[i];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<0)throw Error(`cannot get valid size from specified dimension range. Most likely the range contains negative values in them.`);r*=Number(e[i])}return r}static computeStrides(e){let t=e.length;if(t===0)return[];if(t===1)return[1];let n=Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw Error(`unsupported axis for this operation.`);return e<0?e+t:e}static normalizeAxes(e,t){return e.map(n=>this.normalizeAxis(n,t??e.length))}static sortBasedOnPerm(e,t){return t?t.map(t=>e[t]):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map((e,r)=>e+t[r]+t[r+n])}static areEqual(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}},nW=class e{static adjustPoolAttributes(e,t,n,r,i,a){if(!e&&n.length!==t.length-2)throw Error(`length of specified kernel shapes should be 2 less than length of input dimensions`);if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw Error(`strides should be greater than or equal to 1`)}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw Error(`dilations should be greater than or equal to 1`)}else i.push(1);for(let e=0;e<n.length*2;e++)if(e<a.length){if(a[e]<0)throw Error(`pad should be greater than or equal to 1`)}else a.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw Error(`kernel shapes need to be greater than 0`);if(a[e]>=n[e]||a[e+n.length]>=n[e])throw Error(`pads should be smaller than kernel`)}}static adjustPadsBasedOnAutoPad(t,n,r,i,a,o,s){if(s){if(a.length!==2*(t.length-2))throw Error(`length of pads should be twice the length of data dimensions`);if(n.length!==t.length-2)throw Error(`length of strides should be the length of data dimensions`);if(i.length!==t.length-2)throw Error(`length of kernel shapes should be the length of data dimensions`);for(let c=0;c<t.length-2;c++)e.adjustPadAndReturnShape(t[c+(o?1:2)],n[c],r[c],i[c],a,c,c+t.length-2,s)}}static computePoolOutputShape(t,n,r,i,a,o,s){if(n.length<=0)throw Error(`input shape must be of size greater than 0`);let c=[n[0],n[1]];return e.computeShapeHelper(t,n,c,r,i,a,o,s),c}static computeConvOutputShape(t,n,r,i,a,o,s){if(t.length<=0||n.length<=0)throw Error(`invalid input tensor dims or invalid filter tensor dims`);let c=[t[0],n[0]];return e.computeShapeHelper(!1,t,c,r,i,a,o,s),c}static computeShapeHelper(t,n,r,i,a,o,s,c){if(t)for(let e=0;e<n.length-2;e++)r.push(1);else for(let t=0;t<n.length-2;t++)r.push(e.adjustPadAndReturnShape(n[t+2],i[t],a[t],o[t],s,t,t+n.length-2,c))}static adjustPadAndReturnShape(e,t,n,r,i,a,o,s){let c=n*(r-1)+1;if(s&&s!==`NOTSET`)switch(s){case`VALID`:return i[a]=0,i[o]=0,Math.floor((e-c)/t+1);case`SAME_LOWER`:case`SAME_UPPER`:if(n!==1)throw Error(`Dilation not supported for SAME_UPPER or SAME_LOWER`);{let n=((e+t-1)/t-1)*t+r-e;return i[a]=Math.floor(s===`SAME_LOWER`?(n+1)/2:n/2),i[o]=n-i[a],Math.floor((e+n-r)/t+1)}default:throw Error(`Unsupported AutoPad type`)}else return Math.floor((e+i[a]+i[o]-c)/t+1)}},rW=class{static getShapeOfGemmResult(e,t,n,r,i){if(e.length!==2||n.length!==2)throw Error(`shape need to be of size 2`);let a,o,s;t?(a=e[1],o=e[0]):(a=e[0],o=e[1]);let c=-1;if(r?(s=n[0],c=1):(s=n[1],c=0),n[c]!==o)throw Error(`dimension mismatch`);if(a<=0||s<=0||o<=0)throw Error(`invalid shape specified`);if(i&&!tW.isValidBroadcast(i,[a,s]))throw Error(`gemm: invalid bias shape for broadcast`);return[a,s,o]}},iW=-34028234663852886e22,aW=34028234663852886e22}),sW,cW=Z(()=>{UU(),sW=(e,t)=>new(RU(t))(e)}),lW,uW,dW,fW,pW,mW,hW,gW,_W,vW,yW,bW=Z(()=>{UU(),$U(),lW=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),uW=(e,t)=>{if(t===`int32`)return e;let n=lW.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(RU(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||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'`)}},dW=(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}`)}},fW=1,pW=()=>fW++,mW=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),hW=(e,t)=>{let n=lW.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},gW=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 hW(this.dataType,this.tensorShape)}destroy(){QU(`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=dW(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}},_W=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=mW.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);QU(`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!==hW(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=uW(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 QU(`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?dW(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()}},vW=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=pW();return this.tensorTrackersById.set(e,new _W(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){QU(`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){QU(`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=pW(),o=new gW({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new _W(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)){QU(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}QU(`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 gW({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)}},yW=(...e)=>new vW(...e)}),xW,SW,CW,wW=Z(()=>{UU(),xU(),cW(),bW(),$U(),xW=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),SW=(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])},CW=class{constructor(e){this.tensorManager=yW(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,XU(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){QU(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){QU(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)QU(`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=>SW(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){QU(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=xW.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){QU(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=xW.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(!bU().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);QU(`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 sW(n,t)}}registerMLTensor(e,t,n,r){let i=xW.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return QU(`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=uW(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 QU(`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=xW.get(FU(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),TW=Z(()=>{}),EW,DW,OW,kW,AW,jW,MW,NW,PW,FW=Z(()=>{$U(),TW(),EW=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),DW=[],OW=e=>Math.ceil(Number(e)/16)*16,kW=e=>{for(let t=0;t<DW.length;t++){let n=DW[t];if(e<=n)return n}return Math.ceil(e/16)*16},AW=1,jW=()=>AW++,MW=async(e,t,n,r)=>{let i=OW(n),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let s=a.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(s,0,n)),e}else return new Uint8Array(s.slice(0,n))}finally{a.destroy()}},NW=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[e]of EW)DW.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,r=t.byteOffset,i=t.byteLength,a=OW(i),o=this.storageCache.get(e);if(!o)throw Error(`gpu data for uploading does not exist`);if(Number(o.originalSize)!==i)throw Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let s=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=s.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,r,i)),s.unmap();let l=this.backend.device.createCommandEncoder();l.copyBufferToBuffer(s,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([l.finish()]),s.destroy(),QU(`verbose`,()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw Error(`source gpu data for memcpy does not exist`);let r=this.storageCache.get(t);if(!r)throw Error(`destination gpu data for memcpy does not exist`);if(n.originalSize!==r.originalSize)throw Error(`inconsistent source and destination gpu data size`);let i=OW(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(e,t,n){let r;if(n){if(r=n[0],e===n[1])return QU(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw Error(`Registering a different external buffer under graph capture mode is not supported yet.
12832
+ Please use the previous external buffer!`)}else r=jW();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),QU(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`),r}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),QU(`verbose`,()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=kW(e),r,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let e=(i?this.freeBuffers:this.freeUniformBuffers).get(n);r=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:n,usage:t})}else r=this.backend.device.createBuffer({size:n,usage:t});let o={id:jW(),type:0,buffer:r};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),QU(`verbose`,()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e==`bigint`?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw Error(`releasing data does not exist`)}return QU(`verbose`,()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw Error(`data does not exist`);await MW(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=EW.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(e=>{e.destroy()}),this.capturedPendingBuffers.delete(e)),--this.sessionCount,this.sessionCount===0&&(QU(`warning`,()=>`[WebGPU] Clearing webgpu buffer cache`),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.storageCache=new Map)}},PW=(...e)=>new NW(...e)}),IW,LW,RW=Z(()=>{IW=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(`;`),this.key}},LW=e=>new IW(e)}),zW,BW,VW,HW,UW,WW,GW,KW,qW,JW,YW,$,XW,ZW,QW,$W,eG,tG=Z(()=>{UU(),oW(),zW=64,BW=(e,t)=>{if(t===3)throw Error(`vec3 has same alignment as vec4, use vec4 instead`);switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:`f16`;case 1:return t>1?`vec${t}<f32>`:`f32`;case 6:return t>1?`vec${t}<i32>`:`i32`;case 12:return t>1?`vec${t}<u32>`:`u32`;case 7:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`i32`];case 13:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`u32`];case 9:if(t!==4)throw Error(`bool must be vec4`);return[`u32`,`vec4<bool>`];case 22:return`i32`;case 21:return`u32`;default:throw Error(`Unknown data type: ${e}`)}},VW=(e,t=1)=>{let n=BW(e,t);return typeof n==`string`?n:n[0]},HW=(e,t=1)=>{let n=BW(e,t);return typeof n==`string`?n:n[1]},UW=(...e)=>{let t=[];return e.forEach(e=>{e.length!==0&&t.push({type:12,data:e},{type:12,data:Q.computeStrides(e)})}),t},WW=e=>e%4==0?4:e%2==0?2:1,GW=(e=`f32`,t,n=`0`)=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,KW=(e,t,n)=>e===`f32`?n:t===1?`f32(${n})`:`vec${t}<f32>(${n})`,qW=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,JW=(e,t,n,r)=>e.startsWith(`uniforms.`)&&n>4?typeof t==`string`?r===`f16`?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:r===`f16`?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,YW=(e,t,n,r,i)=>{let a=typeof n==`number`,o=a?n:n.length,s=[...Array(o).keys()],c=o<2?`u32`:o<=4?`vec${o}<u32>`:`array<u32, ${o}>`,l=BW(t,i),u=typeof l==`string`?l:l[1],d={indices:c,value:u,storage:typeof l==`string`?l:l[0],tensor:t},f=e=>typeof e==`string`?e:`${e}u`,p={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},m=a?`uniforms.`:``,h=`${m}${e}_shape`,g=`${m}${e}_strides`,_=``;for(let e=0;e<o-1;e++)_+=`
12833
+ let dim${e} = current / ${JW(g,e,o)};
12834
+ let rest${e} = current % ${JW(g,e,o)};
12835
12835
  indices[${e}] = dim${e};
12836
12836
  current = rest${e};
12837
12837
  `;_+=`indices[${o-1}] = current;`;let v=o<2?``:`
@@ -12840,10 +12840,10 @@ void main() {
12840
12840
  var current = offset;
12841
12841
  ${_}
12842
12842
  return indices;
12843
- }`,y=t=>(p.offsetToIndices=!0,o<2?t:`o2i_${e}(${t})`),b=[];if(o>=2)for(let e=o-1;e>=0;e--)b.push(`${KW(g,e,o)} * (indices[${e}])`);let x=o<2?``:`
12843
+ }`,y=t=>(p.offsetToIndices=!0,o<2?t:`o2i_${e}(${t})`),b=[];if(o>=2)for(let e=o-1;e>=0;e--)b.push(`${JW(g,e,o)} * (indices[${e}])`);let x=o<2?``:`
12844
12844
  fn i2o_${e}(indices: ${d.indices}) -> u32 {
12845
12845
  return ${b.join(`+`)};
12846
- }`,S=t=>(p.indicesToOffset=!0,o<2?t:`i2o_${e}(${t})`),C=(...e)=>o===0?`0u`:`${d.indices}(${e.map(f).join(`,`)})`,w=(e,t)=>o<2?`${e}`:`${KW(e,t,o)}`,T=(e,t,n)=>o<2?`${e}=${n};`:`${KW(e,t,o)}=${n};`,E={},D=(t,n)=>{p.broadcastedIndicesToOffset=!0;let r=`${n.name}broadcastedIndicesTo${e}Offset`;if(r in E)return`${r}(${t})`;let i=[];for(let e=o-1;e>=0;e--){let t=n.indicesGet(`outputIndices`,e+n.rank-o);i.push(`${w(g,e)} * (${t} % ${w(h,e)})`)}return E[r]=`fn ${r}(outputIndices: ${n.type.indices}) -> u32 {
12846
+ }`,S=t=>(p.indicesToOffset=!0,o<2?t:`i2o_${e}(${t})`),C=(...e)=>o===0?`0u`:`${d.indices}(${e.map(f).join(`,`)})`,w=(e,t)=>o<2?`${e}`:`${JW(e,t,o)}`,T=(e,t,n)=>o<2?`${e}=${n};`:`${JW(e,t,o)}=${n};`,E={},D=(t,n)=>{p.broadcastedIndicesToOffset=!0;let r=`${n.name}broadcastedIndicesTo${e}Offset`;if(r in E)return`${r}(${t})`;let i=[];for(let e=o-1;e>=0;e--){let t=n.indicesGet(`outputIndices`,e+n.rank-o);i.push(`${w(g,e)} * (${t} % ${w(h,e)})`)}return E[r]=`fn ${r}(outputIndices: ${n.type.indices}) -> u32 {
12847
12847
  return ${i.length>0?i.join(`+`):`0u`};
12848
12848
  }`,`${r}(${t})`},O=(t,n)=>(()=>{if(d.storage===d.value)return`${e}[${t}]=${n};`;if(d.storage===`vec2<u32>`&&d.value===`i32`)return`${e}[${t}]=vec2<u32>(u32(${n}), select(0u, 0xFFFFFFFFu, ${n} < 0));`;if(d.storage===`vec2<u32>`&&d.value===`u32`)return`${e}[${t}]=vec2<u32>(u32(${n}), 0u);`;if(d.storage===`u32`&&d.value===`vec4<bool>`)return`${e}[${t}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${n}));`;throw Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),k=t=>(()=>{if(d.storage===d.value)return`${e}[${t}]`;if(d.storage===`vec2<u32>`&&d.value===`i32`)return`i32(${e}[${t}].x)`;if(d.storage===`vec2<u32>`&&d.value===`u32`)return`u32(${e}[${t}].x)`;if(d.storage===`u32`&&d.value===`vec4<bool>`)return`vec4<bool>(bool(${e}[${t}] & 0xFFu), bool(${e}[${t}] & 0xFF00u), bool(${e}[${t}] & 0xFF0000u), bool(${e}[${t}] & 0xFF000000u))`;throw Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),A=o<2?``:`
12849
12849
  fn get_${e}ByIndices(indices: ${d.indices}) -> ${u} {
@@ -12858,7 +12858,7 @@ void main() {
12858
12858
  fn set_${e}(${s.map(e=>`d${e}: u32`).join(`, `)}, value: ${u}) {
12859
12859
  set_${e}ByIndices(${C(s.map(e=>`d${e}`).join(`, `))}, value);
12860
12860
  }`;return{impl:()=>{let e=[],t=!1;return p.offsetToIndices&&(e.push(v),t=!0),p.indicesToOffset&&(e.push(x),t=!0),p.broadcastedIndicesToOffset&&(Object.values(E).forEach(t=>e.push(t)),t=!0),p.set&&(e.push(F),t=!0),p.setByIndices&&(e.push(P),t=!0),p.get&&(e.push(j),t=!0),p.getByIndices&&(e.push(A),t=!0),!a&&t&&e.unshift(`const ${h} = ${d.indices}(${n.join(`,`)});`,`const ${g} = ${d.indices}(${Q.computeStrides(n).join(`,`)});`),e.join(`
12861
- `)},type:d,offsetToIndices:y,indicesToOffset:S,broadcastedIndicesToOffset:D,indices:C,indicesGet:w,indicesSet:T,set:(...t)=>{if(t.length!==o+1)throw Error(`indices length must be ${o}`);let n=t[o];if(typeof n!=`string`)throw Error(`value must be string`);let r=t.slice(0,o).map(f).join(`,`);return o===0?O(`0u`,n):o===1?O(r[0],n):(p.set=!0,p.setByIndices=!0,p.indicesToOffset=!0,`set_${e}(${r}, ${n})`)},setByOffset:O,setByIndices:(t,n)=>o<2?O(t,n):(p.setByIndices=!0,p.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:M,getByOffset:k,getByIndices:N,usage:r,name:e,strides:g,shape:h,rank:o}},$=(e,t,n,r=1)=>qW(e,t,n,`input`,r),JW=(e,t,n,r=1)=>qW(e,t,n,`output`,r),YW=(e,t,n)=>qW(e,t,n,`atomicOutput`,1),XW=(e,t,n,r=1)=>qW(e,t,n,`internal`,r),ZW=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e==`number`?`${e}u`:e}) { return; }`}mainStart(e=LW){let t=typeof e==`number`?e:e[0],n=typeof e==`number`?1:e[1],r=typeof e==`number`?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*r>this.limits.maxComputeInvocationsPerWorkgroup)throw Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1;return`@compute @workgroup_size(${t}, ${n}, ${r})
12861
+ `)},type:d,offsetToIndices:y,indicesToOffset:S,broadcastedIndicesToOffset:D,indices:C,indicesGet:w,indicesSet:T,set:(...t)=>{if(t.length!==o+1)throw Error(`indices length must be ${o}`);let n=t[o];if(typeof n!=`string`)throw Error(`value must be string`);let r=t.slice(0,o).map(f).join(`,`);return o===0?O(`0u`,n):o===1?O(r[0],n):(p.set=!0,p.setByIndices=!0,p.indicesToOffset=!0,`set_${e}(${r}, ${n})`)},setByOffset:O,setByIndices:(t,n)=>o<2?O(t,n):(p.setByIndices=!0,p.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:M,getByOffset:k,getByIndices:N,usage:r,name:e,strides:g,shape:h,rank:o}},$=(e,t,n,r=1)=>YW(e,t,n,`input`,r),XW=(e,t,n,r=1)=>YW(e,t,n,`output`,r),ZW=(e,t,n)=>YW(e,t,n,`atomicOutput`,1),QW=(e,t,n,r=1)=>YW(e,t,n,`internal`,r),$W=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e==`number`?`${e}u`:e}) { return; }`}mainStart(e=zW){let t=typeof e==`number`?e:e[0],n=typeof e==`number`?1:e[1],r=typeof e==`number`?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*r>this.limits.maxComputeInvocationsPerWorkgroup)throw Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1;return`@compute @workgroup_size(${t}, ${n}, ${r})
12862
12862
  fn main(${i?`@builtin(global_invocation_id) global_id : vec3<u32>,
12863
12863
  @builtin(workgroup_id) workgroup_id : vec3<u32>,
12864
12864
  @builtin(local_invocation_index) local_idx : u32,
@@ -12876,13 +12876,13 @@ void main() {
12876
12876
  struct Uniforms { ${e.join(`, `)} };
12877
12877
  @group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(`
12878
12878
  `)+this.internalVariables.map(e=>e.impl()).join(`
12879
- `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=e=>[12,10,1,6][[`u32`,`f16`,`f32`,`i32`].indexOf(e)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},QW=(e,t)=>new ZW(e,t)}),eG,tG,nG,rG,iG,aG,oG,sG,cG,lG=Z(()=>{VU(),iW(),IW(),$W(),eG=(e,t)=>{if(!e||e.length!==1)throw Error(`Transpose requires 1 input.`);if(t.length!==0&&t.length!==e[0].dims.length)throw Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},tG=(e,t)=>t.length===0?[...Array(e).keys()].reverse():t,nG=(e,t)=>Q.sortBasedOnPerm(e,tG(e.length,t)),rG=(e,t,n,r)=>{let i=`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {
12880
- var a: ${n.type.indices};`;for(let n=0;n<t;++n)i+=`a[${e[n]}]=i[${n}];`;return i+=`return a;}`},iG=(e,t)=>{let n=[],r=[];for(let i=0;i<e.length;++i)e[i]!==1&&n.push(e[i]),e[t[i]]!==1&&r.push(t[i]);return{newShape:n,newPerm:r}},aG=(e,t)=>{let n=0;for(let r=0;r<e.length;++r)if(t[e[r]]!==1){if(e[r]<n)return!1;n=e[r]}return!0},oG=(e,t)=>{let n=e.dataType,r=e.dims.length,i=tG(r,t),a=nG(e.dims,i),o=e.dims,s=a,c=r<2||aG(i,e.dims),l;if(c)return l=e=>{let t=$(`input`,n,o,4),r=JW(`output`,n,s,4);return`
12879
+ `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=e=>[12,10,1,6][[`u32`,`f16`,`f32`,`i32`].indexOf(e)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},eG=(e,t)=>new $W(e,t)}),nG,rG,iG,aG,oG,sG,cG,lG,uG,dG=Z(()=>{UU(),oW(),RW(),tG(),nG=(e,t)=>{if(!e||e.length!==1)throw Error(`Transpose requires 1 input.`);if(t.length!==0&&t.length!==e[0].dims.length)throw Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},rG=(e,t)=>t.length===0?[...Array(e).keys()].reverse():t,iG=(e,t)=>Q.sortBasedOnPerm(e,rG(e.length,t)),aG=(e,t,n,r)=>{let i=`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {
12880
+ var a: ${n.type.indices};`;for(let n=0;n<t;++n)i+=`a[${e[n]}]=i[${n}];`;return i+=`return a;}`},oG=(e,t)=>{let n=[],r=[];for(let i=0;i<e.length;++i)e[i]!==1&&n.push(e[i]),e[t[i]]!==1&&r.push(t[i]);return{newShape:n,newPerm:r}},sG=(e,t)=>{let n=0;for(let r=0;r<e.length;++r)if(t[e[r]]!==1){if(e[r]<n)return!1;n=e[r]}return!0},cG=(e,t)=>{let n=e.dataType,r=e.dims.length,i=rG(r,t),a=iG(e.dims,i),o=e.dims,s=a,c=r<2||sG(i,e.dims),l;if(c)return l=e=>{let t=$(`input`,n,o,4),r=XW(`output`,n,s,4);return`
12881
12881
  ${e.registerUniform(`output_size`,`u32`).declareVariables(t,r)}
12882
12882
  ${e.mainStart()}
12883
12883
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
12884
12884
  output[global_idx] = input[global_idx];
12885
- }`},{name:`TransposeCopy`,shaderCache:{inputDependencies:[`type`]},getRunData:()=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64/4)},programUniforms:[{type:12,data:Math.ceil(t/4)}]}},getShaderSource:l};let{newShape:u,newPerm:d}=iG(e.dims,i),f=Q.areEqual(d,[2,3,1]),p=Q.areEqual(d,[3,1,2]);return u.length===2||f||p?(o=f?[u[0],u[1]*u[2]]:p?[u[0]*u[1],u[2]]:u,s=[o[1],o[0]],l=e=>{let t=$(`a`,n,o.length),r=JW(`output`,n,s.length);return`
12885
+ }`},{name:`TransposeCopy`,shaderCache:{inputDependencies:[`type`]},getRunData:()=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64/4)},programUniforms:[{type:12,data:Math.ceil(t/4)}]}},getShaderSource:l};let{newShape:u,newPerm:d}=oG(e.dims,i),f=Q.areEqual(d,[2,3,1]),p=Q.areEqual(d,[3,1,2]);return u.length===2||f||p?(o=f?[u[0],u[1]*u[2]]:p?[u[0]*u[1],u[2]]:u,s=[o[1],o[0]],l=e=>{let t=$(`a`,n,o.length),r=XW(`output`,n,s.length);return`
12886
12886
  ${e.registerUniform(`output_size`,`u32`).declareVariables(t,r)}
12887
12887
  var<workgroup> tile : array<array<${r.type.value}, 17>, 16>;
12888
12888
  ${e.mainStart([16,16,1])}
@@ -12901,10 +12901,10 @@ void main() {
12901
12901
  if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
12902
12902
  ${r.setByIndices(`${r.type.indices}(output_row, output_col)`,`tile[local_id.x][local_id.y]`)}
12903
12903
  }
12904
- }`},{name:`TransposeShared`,shaderCache:{inputDependencies:[`type`]},getRunData:()=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(s[1]/16),y:Math.ceil(s[0]/16)},programUniforms:[{type:12,data:t},...VW(o,s)]}},getShaderSource:l}):(l=e=>{let t=$(`a`,n,o.length),a=JW(`output`,n,s.length);return`
12904
+ }`},{name:`TransposeShared`,shaderCache:{inputDependencies:[`type`]},getRunData:()=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(s[1]/16),y:Math.ceil(s[0]/16)},programUniforms:[{type:12,data:t},...UW(o,s)]}},getShaderSource:l}):(l=e=>{let t=$(`a`,n,o.length),a=XW(`output`,n,s.length);return`
12905
12905
  ${e.registerUniform(`output_size`,`u32`).declareVariables(t,a)}
12906
12906
 
12907
- ${rG(i,r,t,a)}
12907
+ ${aG(i,r,t,a)}
12908
12908
 
12909
12909
  ${e.mainStart()}
12910
12910
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -12913,7 +12913,7 @@ void main() {
12913
12913
  let aIndices = perm(indices);
12914
12914
 
12915
12915
  ${a.setByOffset(`global_idx`,t.getByIndices(`aIndices`))}
12916
- }`},{name:`Transpose`,shaderCache:{hint:`${t}`,inputDependencies:[`rank`]},getRunData:()=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:[{type:12,data:t},...VW(o,s)]}},getShaderSource:l})},sG=(e,t)=>{eG(e.inputs,t.perm),e.compute(oG(e.inputs[0],t.perm))},cG=e=>FW({perm:e.perm})}),uG,dG,fG,pG,mG,hG,gG,_G,vG,yG,bG,xG,SG,CG,wG,TG,EG,DG,OG,kG,AG,jG=Z(()=>{VU(),iW(),$W(),iK(),lG(),uG={max:`select(bestValue, candidate, candidate > bestValue)`,min:`select(bestValue, candidate, candidate < bestValue)`,mean:`bestValue + candidate`,sum:`bestValue + candidate`,prod:`bestValue * candidate`,sumSquare:`bestValue + candidate * candidate`,logSumExp:`bestValue + exp(candidate)`,l1:`bestValue + abs(candidate)`,l2:`bestValue + candidate * candidate`,logSum:`bestValue + candidate`},dG={max:`select(bestValue, candidate, candidate > bestValue)`,min:`select(bestValue, candidate, candidate < bestValue)`,mean:`bestValue + candidate`,sum:`bestValue + candidate`,prod:`bestValue * candidate`,sumSquare:`bestValue + candidate`,logSumExp:`bestValue + candidate`,l1:`bestValue + candidate`,l2:`bestValue + candidate`,logSum:`bestValue + candidate`},fG={max:`_A[offset]`,min:`_A[offset]`,mean:`0`,sum:`0`,prod:`1`,sumSquare:`0`,logSumExp:`0`,l1:`0`,l2:`0`,logSum:`0`},pG={max:`bestValue`,min:`bestValue`,sum:`bestValue`,prod:`bestValue`,sumSquare:`bestValue`,logSumExp:`log(bestValue)`,l1:`bestValue`,l2:`sqrt(bestValue)`,logSum:`log(bestValue)`},mG=(e,t)=>{let n=[];for(let r=t-e;r<t;++r)n.push(r);return n},hG=(e,t)=>{let n=[],r=e.length;for(let i=0;i<r;i++)t.indexOf(i)===-1&&n.push(e[i]);return[n,t.map(t=>e[t])]},gG=(e,t)=>{let n=e.length+t.length,r=[],i=0;for(let a=0;a<n;a++)t.indexOf(a)===-1?r.push(e[i++]):r.push(1);return r},_G=(e,t)=>{for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0},vG=(e,t)=>{let n=[];if(!_G(e,t)){for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);e.forEach(e=>n.push(e))}return n},yG=(e,t,n,r,i,a,o)=>{let s=n[0].dims,c=Q.size(a),l=Q.size(o),u=$(`_A`,n[0].dataType,s),d=JW(`output`,i,a),f=64;c===1&&(f=256);let p=`
12916
+ }`},{name:`Transpose`,shaderCache:{hint:`${t}`,inputDependencies:[`rank`]},getRunData:()=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:[{type:12,data:t},...UW(o,s)]}},getShaderSource:l})},lG=(e,t)=>{nG(e.inputs,t.perm),e.compute(cG(e.inputs[0],t.perm))},uG=e=>LW({perm:e.perm})}),fG,pG,mG,hG,gG,_G,vG,yG,bG,xG,SG,CG,wG,TG,EG,DG,OG,kG,AG,jG,MG,NG=Z(()=>{UU(),oW(),tG(),oK(),dG(),fG={max:`select(bestValue, candidate, candidate > bestValue)`,min:`select(bestValue, candidate, candidate < bestValue)`,mean:`bestValue + candidate`,sum:`bestValue + candidate`,prod:`bestValue * candidate`,sumSquare:`bestValue + candidate * candidate`,logSumExp:`bestValue + exp(candidate)`,l1:`bestValue + abs(candidate)`,l2:`bestValue + candidate * candidate`,logSum:`bestValue + candidate`},pG={max:`select(bestValue, candidate, candidate > bestValue)`,min:`select(bestValue, candidate, candidate < bestValue)`,mean:`bestValue + candidate`,sum:`bestValue + candidate`,prod:`bestValue * candidate`,sumSquare:`bestValue + candidate`,logSumExp:`bestValue + candidate`,l1:`bestValue + candidate`,l2:`bestValue + candidate`,logSum:`bestValue + candidate`},mG={max:`_A[offset]`,min:`_A[offset]`,mean:`0`,sum:`0`,prod:`1`,sumSquare:`0`,logSumExp:`0`,l1:`0`,l2:`0`,logSum:`0`},hG={max:`bestValue`,min:`bestValue`,sum:`bestValue`,prod:`bestValue`,sumSquare:`bestValue`,logSumExp:`log(bestValue)`,l1:`bestValue`,l2:`sqrt(bestValue)`,logSum:`log(bestValue)`},gG=(e,t)=>{let n=[];for(let r=t-e;r<t;++r)n.push(r);return n},_G=(e,t)=>{let n=[],r=e.length;for(let i=0;i<r;i++)t.indexOf(i)===-1&&n.push(e[i]);return[n,t.map(t=>e[t])]},vG=(e,t)=>{let n=e.length+t.length,r=[],i=0;for(let a=0;a<n;a++)t.indexOf(a)===-1?r.push(e[i++]):r.push(1);return r},yG=(e,t)=>{for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0},bG=(e,t)=>{let n=[];if(!yG(e,t)){for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);e.forEach(e=>n.push(e))}return n},xG=(e,t,n,r,i,a,o)=>{let s=n[0].dims,c=Q.size(a),l=Q.size(o),u=$(`_A`,n[0].dataType,s),d=XW(`output`,i,a),f=64;c===1&&(f=256);let p=`
12917
12917
  var<workgroup> aBestValues : array<f32, ${f}>;
12918
12918
  `;return{name:e,shaderCache:{hint:`${t};${f}`,inputDependencies:[`type`]},getShaderSource:e=>`
12919
12919
  ${e.registerUniform(`reduceSize`,`u32`).declareVariables(u,d)}
@@ -12926,11 +12926,11 @@ void main() {
12926
12926
  let outputIndex = global_idx / ${f};
12927
12927
  let offset = outputIndex * uniforms.reduceSize;
12928
12928
 
12929
- var bestValue = f32(${fG[r]});
12929
+ var bestValue = f32(${mG[r]});
12930
12930
  let Length = uniforms.reduceSize;
12931
12931
  for (var k = local_idx; k < Length; k = k + ${f}) {
12932
12932
  let candidate = f32(${u.getByOffset(`offset + k`)});
12933
- bestValue = ${uG[r]};
12933
+ bestValue = ${fG[r]};
12934
12934
  }
12935
12935
  aBestValues[local_idx] = bestValue;
12936
12936
  workgroupBarrier();
@@ -12941,7 +12941,7 @@ void main() {
12941
12941
  let interval = DIV_CEIL(reduceSize, 2u);
12942
12942
  if (local_idx < currentSize) {
12943
12943
  let candidate = aBestValues[local_idx + interval];
12944
- bestValue = ${dG[r]};
12944
+ bestValue = ${pG[r]};
12945
12945
  aBestValues[local_idx] = bestValue;
12946
12946
  }
12947
12947
  reduceSize = interval;
@@ -12949,9 +12949,9 @@ void main() {
12949
12949
  }
12950
12950
 
12951
12951
  if (local_idx == 0u) {
12952
- ${d.setByOffset(`outputIndex`,`${r===`mean`?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${pG[r]})`}`)};
12952
+ ${d.setByOffset(`outputIndex`,`${r===`mean`?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${hG[r]})`}`)};
12953
12953
  }
12954
- }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:c},programUniforms:[{type:12,data:l}]})}},bG=(e,t,n,r)=>{let i=e.inputs.length===1?n:FG(e.inputs,n),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((e,t)=>t));let o=Q.normalizeAxes(a,e.inputs[0].dims.length),s=o,c=e.inputs[0],l=vG(s,e.inputs[0].dims.length);l.length>0&&(c=e.compute(oG(e.inputs[0],l),{inputs:[0],outputs:[-1]})[0],s=mG(s.length,c.dims.length));let[u,d]=hG(c.dims,s),f=u;i.keepDims&&(f=gG(u,o)),e.compute(yG(t,i.cacheKey,[c],r,e.inputs[0].dataType,f,d),{inputs:[c]})},xG=(e,t)=>{bG(e,`ReduceMeanShared`,t,`mean`)},SG=(e,t)=>{bG(e,`ReduceL1Shared`,t,`l1`)},CG=(e,t)=>{bG(e,`ReduceL2Shared`,t,`l2`)},wG=(e,t)=>{bG(e,`ReduceLogSumExpShared`,t,`logSumExp`)},TG=(e,t)=>{bG(e,`ReduceMaxShared`,t,`max`)},EG=(e,t)=>{bG(e,`ReduceMinShared`,t,`min`)},DG=(e,t)=>{bG(e,`ReduceProdShared`,t,`prod`)},OG=(e,t)=>{bG(e,`ReduceSumShared`,t,`sum`)},kG=(e,t)=>{bG(e,`ReduceSumSquareShared`,t,`sumSquare`)},AG=(e,t)=>{bG(e,`ReduceLogSumShared`,t,`logSum`)}}),MG,NG,PG,FG,IG,LG,RG,zG,BG,VG,HG,UG,WG,GG,KG,qG,JG,YG,XG,ZG,QG,$G,eK,tK,nK,rK,iK=Z(()=>{VU(),iW(),IW(),$W(),jG(),MG=e=>{if(!e||e.length===0||e.length>2)throw Error(`Reduce op requires 1 or 2 inputs.`);if(e.length===2&&e[1].dims.length!==1)throw Error(`Invalid axes input dims.`)},NG=e=>[``,``,`var value = ${e.getByIndices(`input_indices`)};`,``],PG=(e,t,n,r,i,a,o=!1,s=!1)=>{let c=[],l=n[0].dims,u=l.length,d=Q.normalizeAxes(i,u),f=!s&&d.length===0;l.forEach((e,t)=>{f||d.indexOf(t)>=0?o&&c.push(1):c.push(e)});let p=c.length,m=Q.size(c);return{name:e,shaderCache:t,getShaderSource:e=>{let t=[],i=$(`_A`,n[0].dataType,u),s=JW(`output`,a,p),c=r(i,s,d),m=c[2];for(let e=0,n=0;e<u;e++)f||d.indexOf(e)>=0?(o&&n++,m=`for(var j${e}: u32 = 0; j${e} < ${l[e]}; j${e}++) {
12954
+ }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:c},programUniforms:[{type:12,data:l}]})}},SG=(e,t,n,r)=>{let i=e.inputs.length===1?n:LG(e.inputs,n),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((e,t)=>t));let o=Q.normalizeAxes(a,e.inputs[0].dims.length),s=o,c=e.inputs[0],l=bG(s,e.inputs[0].dims.length);l.length>0&&(c=e.compute(cG(e.inputs[0],l),{inputs:[0],outputs:[-1]})[0],s=gG(s.length,c.dims.length));let[u,d]=_G(c.dims,s),f=u;i.keepDims&&(f=vG(u,o)),e.compute(xG(t,i.cacheKey,[c],r,e.inputs[0].dataType,f,d),{inputs:[c]})},CG=(e,t)=>{SG(e,`ReduceMeanShared`,t,`mean`)},wG=(e,t)=>{SG(e,`ReduceL1Shared`,t,`l1`)},TG=(e,t)=>{SG(e,`ReduceL2Shared`,t,`l2`)},EG=(e,t)=>{SG(e,`ReduceLogSumExpShared`,t,`logSumExp`)},DG=(e,t)=>{SG(e,`ReduceMaxShared`,t,`max`)},OG=(e,t)=>{SG(e,`ReduceMinShared`,t,`min`)},kG=(e,t)=>{SG(e,`ReduceProdShared`,t,`prod`)},AG=(e,t)=>{SG(e,`ReduceSumShared`,t,`sum`)},jG=(e,t)=>{SG(e,`ReduceSumSquareShared`,t,`sumSquare`)},MG=(e,t)=>{SG(e,`ReduceLogSumShared`,t,`logSum`)}}),PG,FG,IG,LG,RG,zG,BG,VG,HG,UG,WG,GG,KG,qG,JG,YG,XG,ZG,QG,$G,eK,tK,nK,rK,iK,aK,oK=Z(()=>{UU(),oW(),RW(),tG(),NG(),PG=e=>{if(!e||e.length===0||e.length>2)throw Error(`Reduce op requires 1 or 2 inputs.`);if(e.length===2&&e[1].dims.length!==1)throw Error(`Invalid axes input dims.`)},FG=e=>[``,``,`var value = ${e.getByIndices(`input_indices`)};`,``],IG=(e,t,n,r,i,a,o=!1,s=!1)=>{let c=[],l=n[0].dims,u=l.length,d=Q.normalizeAxes(i,u),f=!s&&d.length===0;l.forEach((e,t)=>{f||d.indexOf(t)>=0?o&&c.push(1):c.push(e)});let p=c.length,m=Q.size(c);return{name:e,shaderCache:t,getShaderSource:e=>{let t=[],i=$(`_A`,n[0].dataType,u),s=XW(`output`,a,p),c=r(i,s,d),m=c[2];for(let e=0,n=0;e<u;e++)f||d.indexOf(e)>=0?(o&&n++,m=`for(var j${e}: u32 = 0; j${e} < ${l[e]}; j${e}++) {
12955
12955
  ${c[2].includes(`last_index`)?`let last_index = j${e};`:``}
12956
12956
  ${i.indicesSet(`input_indices`,e,`j${e}`)}
12957
12957
  ${m}
@@ -12972,19 +12972,19 @@ void main() {
12972
12972
  ${c[3]}
12973
12973
  ${c.length===4?s.setByOffset(`global_idx`,`value`):c.slice(4).join(`
12974
12974
  `)}
12975
- }`},getRunData:()=>({outputs:[{dims:c,dataType:a}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...VW(l,c)]})}},FG=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(e=>n.push(Number(e))),FW({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},IG=(e,t,n,r)=>{let i=e.inputs,a=i.length===1?n:FG(i,n);e.compute(PG(t,{hint:a.cacheKey,inputDependencies:[`rank`]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?NG:r,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},LG=(e,t)=>{MG(e.inputs),IG(e,`ReduceLogSum`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += ${e.getByIndices(`input_indices`)};`,`value = log(value);`])},RG=(e,t)=>{MG(e.inputs),IG(e,`ReduceL1`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += abs(${e.getByIndices(`input_indices`)});`,``])},zG=(e,t)=>{MG(e.inputs),IG(e,`ReduceL2`,t,(e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,``,`t = ${e.getByIndices(`input_indices`)}; value += (t * t);`,`value = sqrt(value);`])},BG=(e,t)=>{MG(e.inputs),IG(e,`ReduceLogSumExp`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += exp(${e.getByIndices(`input_indices`)});`,`value = log(value);`])},VG=(e,t)=>{MG(e.inputs),IG(e,`ReduceMax`,t,(e,t,n)=>{let r=[];for(let t=0;t<e.rank;t++)(n.indexOf(t)>=0||n.length===0)&&r.push(e.indicesSet(`input_indices`,t,0));return[`${r.join(`
12976
- `)}`,`var value = ${e.getByIndices(`input_indices`)};`,`value = max(value, ${e.getByIndices(`input_indices`)});`,``]})},HG=(e,t)=>{MG(e.inputs),IG(e,`ReduceMean`,t,(t,n,r)=>{let i=1;for(let n=0;n<t.rank;n++)(r.indexOf(n)>=0||r.length===0)&&(i*=e.inputs[0].dims[n]);return[`var sum = f32(0);`,``,`sum += f32(${t.getByIndices(`input_indices`)});`,`let value = ${n.type.value}(sum / ${i});`]})},UG=(e,t)=>{MG(e.inputs),IG(e,`ReduceMin`,t,(e,t,n)=>{let r=[];for(let t=0;t<e.rank;t++)(n.indexOf(t)>=0||n.length===0)&&r.push(`input_indices[${t}] = 0;`);return[`${r.join(`
12977
- `)}`,`var value = ${e.getByIndices(`input_indices`)};`,`value = min(value, ${e.getByIndices(`input_indices`)});`,``]})},WG=(e,t)=>{MG(e.inputs),IG(e,`ReduceProd`,t,(e,t)=>[`var value = ${t.type.storage}(1);`,``,`value *= ${e.getByIndices(`input_indices`)};`,``])},GG=(e,t)=>{MG(e.inputs),IG(e,`ReduceSum`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += ${e.getByIndices(`input_indices`)};`,``])},KG=(e,t)=>{MG(e.inputs),IG(e,`ReduceSumSquare`,t,(e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,``,`t = ${e.getByIndices(`input_indices`)}; value += t * t;`,``])},qG=(e,t,n)=>{if(t.length===0)return n;let r=1,i=1;for(let n=0;n<t.length;n++)t.indexOf(n)===-1?r*=e[n]:i*=e[n];return i<32&&r>1024},JG=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?HG(e,t):xG(e,t)},YG=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?RG(e,t):SG(e,t)},XG=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zG(e,t):CG(e,t)},ZG=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?BG(e,t):wG(e,t)},QG=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?VG(e,t):TG(e,t)},$G=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?UG(e,t):EG(e,t)},eK=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?WG(e,t):DG(e,t)},tK=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?GG(e,t):OG(e,t)},nK=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?KG(e,t):kG(e,t)},rK=(e,t)=>{qG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?LG(e,t):AG(e,t)}}),aK,oK,sK,cK,lK=Z(()=>{VU(),IW(),iK(),aK=e=>{if(!e||e.length===0||e.length>2)throw Error(`ArgMinMaxOp op requires 1 or 2 inputs.`);if(e[0].dataType!==1)throw Error(`Invalid input type.`)},oK=(e,t)=>{aK(e.inputs),e.compute(PG(`ArgMin`,{hint:t.cacheKey,inputDependencies:[`rank`]},[e.inputs[0]],(e,n,r)=>{let i=[];for(let t=0;t<e.rank;t++)(r.indexOf(t)>=0||r.length===0)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join(`
12975
+ }`},getRunData:()=>({outputs:[{dims:c,dataType:a}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...UW(l,c)]})}},LG=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(e=>n.push(Number(e))),LW({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},RG=(e,t,n,r)=>{let i=e.inputs,a=i.length===1?n:LG(i,n);e.compute(IG(t,{hint:a.cacheKey,inputDependencies:[`rank`]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?FG:r,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},zG=(e,t)=>{PG(e.inputs),RG(e,`ReduceLogSum`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += ${e.getByIndices(`input_indices`)};`,`value = log(value);`])},BG=(e,t)=>{PG(e.inputs),RG(e,`ReduceL1`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += abs(${e.getByIndices(`input_indices`)});`,``])},VG=(e,t)=>{PG(e.inputs),RG(e,`ReduceL2`,t,(e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,``,`t = ${e.getByIndices(`input_indices`)}; value += (t * t);`,`value = sqrt(value);`])},HG=(e,t)=>{PG(e.inputs),RG(e,`ReduceLogSumExp`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += exp(${e.getByIndices(`input_indices`)});`,`value = log(value);`])},UG=(e,t)=>{PG(e.inputs),RG(e,`ReduceMax`,t,(e,t,n)=>{let r=[];for(let t=0;t<e.rank;t++)(n.indexOf(t)>=0||n.length===0)&&r.push(e.indicesSet(`input_indices`,t,0));return[`${r.join(`
12976
+ `)}`,`var value = ${e.getByIndices(`input_indices`)};`,`value = max(value, ${e.getByIndices(`input_indices`)});`,``]})},WG=(e,t)=>{PG(e.inputs),RG(e,`ReduceMean`,t,(t,n,r)=>{let i=1;for(let n=0;n<t.rank;n++)(r.indexOf(n)>=0||r.length===0)&&(i*=e.inputs[0].dims[n]);return[`var sum = f32(0);`,``,`sum += f32(${t.getByIndices(`input_indices`)});`,`let value = ${n.type.value}(sum / ${i});`]})},GG=(e,t)=>{PG(e.inputs),RG(e,`ReduceMin`,t,(e,t,n)=>{let r=[];for(let t=0;t<e.rank;t++)(n.indexOf(t)>=0||n.length===0)&&r.push(`input_indices[${t}] = 0;`);return[`${r.join(`
12977
+ `)}`,`var value = ${e.getByIndices(`input_indices`)};`,`value = min(value, ${e.getByIndices(`input_indices`)});`,``]})},KG=(e,t)=>{PG(e.inputs),RG(e,`ReduceProd`,t,(e,t)=>[`var value = ${t.type.storage}(1);`,``,`value *= ${e.getByIndices(`input_indices`)};`,``])},qG=(e,t)=>{PG(e.inputs),RG(e,`ReduceSum`,t,(e,t)=>[`var value = ${t.type.storage}(0);`,``,`value += ${e.getByIndices(`input_indices`)};`,``])},JG=(e,t)=>{PG(e.inputs),RG(e,`ReduceSumSquare`,t,(e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,``,`t = ${e.getByIndices(`input_indices`)}; value += t * t;`,``])},YG=(e,t,n)=>{if(t.length===0)return n;let r=1,i=1;for(let n=0;n<t.length;n++)t.indexOf(n)===-1?r*=e[n]:i*=e[n];return i<32&&r>1024},XG=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?WG(e,t):CG(e,t)},ZG=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?BG(e,t):wG(e,t)},QG=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?VG(e,t):TG(e,t)},$G=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?HG(e,t):EG(e,t)},eK=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?UG(e,t):DG(e,t)},tK=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?GG(e,t):OG(e,t)},nK=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?KG(e,t):kG(e,t)},rK=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qG(e,t):AG(e,t)},iK=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?JG(e,t):jG(e,t)},aK=(e,t)=>{YG(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zG(e,t):MG(e,t)}}),sK,cK,lK,uK,dK=Z(()=>{UU(),RW(),oK(),sK=e=>{if(!e||e.length===0||e.length>2)throw Error(`ArgMinMaxOp op requires 1 or 2 inputs.`);if(e[0].dataType!==1)throw Error(`Invalid input type.`)},cK=(e,t)=>{sK(e.inputs),e.compute(IG(`ArgMin`,{hint:t.cacheKey,inputDependencies:[`rank`]},[e.inputs[0]],(e,n,r)=>{let i=[];for(let t=0;t<e.rank;t++)(r.indexOf(t)>=0||r.length===0)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join(`
12978
12978
  `)}`,`var value = ${e.getByIndices(`input_indices`)};
12979
12979
  var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLastIndex>0?`<=`:`<`} value) {
12980
12980
  value = ${e.getByIndices(`input_indices`)};
12981
12981
  best_index = i32(last_index);
12982
- }`,``,n.setByOffset(`global_idx`,`best_index`)]},[t.axis],7,t.keepDims),{inputs:[0]})},sK=(e,t)=>{aK(e.inputs),e.compute(PG(`argMax`,{hint:t.cacheKey,inputDependencies:[`rank`]},[e.inputs[0]],(e,n,r)=>{let i=[];for(let t=0;t<e.rank;t++)(r.indexOf(t)>=0||r.length===0)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join(`
12982
+ }`,``,n.setByOffset(`global_idx`,`best_index`)]},[t.axis],7,t.keepDims),{inputs:[0]})},lK=(e,t)=>{sK(e.inputs),e.compute(IG(`argMax`,{hint:t.cacheKey,inputDependencies:[`rank`]},[e.inputs[0]],(e,n,r)=>{let i=[];for(let t=0;t<e.rank;t++)(r.indexOf(t)>=0||r.length===0)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join(`
12983
12983
  `)}`,`var value = ${e.getByIndices(`input_indices`)};
12984
12984
  var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLastIndex>0?`>=`:`>`} value) {
12985
12985
  value = ${e.getByIndices(`input_indices`)};
12986
12986
  best_index = i32(last_index);
12987
- }`,``,n.setByOffset(`global_idx`,`best_index`)]},[t.axis],7,t.keepDims),{inputs:[0]})},cK=e=>FW(e)}),uK,dK,fK,pK,mK,hK,gK,_K,vK=Z(()=>{VU(),iW(),CW(),$W(),uK=(e,t)=>{let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5];if(o&&s)throw Error(`Attention cannot have both past and attention_bias`);if(n.dims.length!==3)throw Error(`Input "input" must have 3 dimensions`);let c=n.dims[0],l=n.dims[1],u=n.dims[2];if(i.dims.length!==1)throw Error(`Input "bias" is expected to have 1 dimensions`);if(r.dims.length!==2)throw Error(`Input "weights" is expected to have 2 dimensions`);if(r.dims[0]!==u)throw Error(`Input 1 dimension 0 should have same length as dimension 2 of input 0`);if(i.dims[0]!==r.dims[1])throw Error(`Input "bias" dimension 0 should have same length as dimension 1 of input "weights"`);let d=i.dims[0]/3,f=d,p=f;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw Error(`qkv_hidden_sizes attribute should have 3 elements`);for(let e of t.qkvHiddenSizes)if(e%t.numHeads!==0)throw Error(`qkv_hidden_sizes should be divisible by num_heads`);d=t.qkvHiddenSizes[0],f=t.qkvHiddenSizes[1],p=t.qkvHiddenSizes[2]}let m=l;if(d!==f)throw Error(`qkv_hidden_sizes first element should be same as the second`);if(i.dims[0]!==d+f+p)throw Error(`Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes`);let h=0;if(o){if(f!==p)throw Error(`Input "past" expect k_hidden_size == v_hidden_size`);if(o.dims.length!==5)throw Error(`Input "past" must have 5 dimensions`);if(o.dims[0]!==2)throw Error(`Input "past" first dimension must be 2`);if(o.dims[1]!==c)throw Error(`Input "past" second dimension must be batch_size`);if(o.dims[2]!==t.numHeads)throw Error(`Input "past" third dimension must be num_heads`);if(o.dims[4]!==f/t.numHeads)throw Error(`Input "past" fifth dimension must be k_hidden_size / num_heads`);t.pastPresentShareBuffer||(h=o.dims[3])}let g=m+h;if(a)throw Error(`Mask not supported`);if(o)throw Error(`past is not supported`);if(s){if(s.dims.length!==4)throw Error(`Input "attention_bias" must have 4 dimensions`);if(s.dims[0]!==c||s.dims[1]!==t.numHeads||s.dims[2]!==l||s.dims[3]!==g)throw Error(`Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)`)}return{batchSize:c,sequenceLength:l,pastSequenceLength:h,kvSequenceLength:m,totalSequenceLength:g,maxSequenceLength:-1,inputHiddenSize:u,hiddenSize:d,vHiddenSize:p,headSize:Math.floor(d/t.numHeads),vHeadSize:Math.floor(p/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},dK=(e,t,n)=>t&&e?`
12987
+ }`,``,n.setByOffset(`global_idx`,`best_index`)]},[t.axis],7,t.keepDims),{inputs:[0]})},uK=e=>LW(e)}),fK,pK,mK,hK,gK,_K,vK,yK,bK=Z(()=>{UU(),oW(),TW(),tG(),fK=(e,t)=>{let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5];if(o&&s)throw Error(`Attention cannot have both past and attention_bias`);if(n.dims.length!==3)throw Error(`Input "input" must have 3 dimensions`);let c=n.dims[0],l=n.dims[1],u=n.dims[2];if(i.dims.length!==1)throw Error(`Input "bias" is expected to have 1 dimensions`);if(r.dims.length!==2)throw Error(`Input "weights" is expected to have 2 dimensions`);if(r.dims[0]!==u)throw Error(`Input 1 dimension 0 should have same length as dimension 2 of input 0`);if(i.dims[0]!==r.dims[1])throw Error(`Input "bias" dimension 0 should have same length as dimension 1 of input "weights"`);let d=i.dims[0]/3,f=d,p=f;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw Error(`qkv_hidden_sizes attribute should have 3 elements`);for(let e of t.qkvHiddenSizes)if(e%t.numHeads!==0)throw Error(`qkv_hidden_sizes should be divisible by num_heads`);d=t.qkvHiddenSizes[0],f=t.qkvHiddenSizes[1],p=t.qkvHiddenSizes[2]}let m=l;if(d!==f)throw Error(`qkv_hidden_sizes first element should be same as the second`);if(i.dims[0]!==d+f+p)throw Error(`Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes`);let h=0;if(o){if(f!==p)throw Error(`Input "past" expect k_hidden_size == v_hidden_size`);if(o.dims.length!==5)throw Error(`Input "past" must have 5 dimensions`);if(o.dims[0]!==2)throw Error(`Input "past" first dimension must be 2`);if(o.dims[1]!==c)throw Error(`Input "past" second dimension must be batch_size`);if(o.dims[2]!==t.numHeads)throw Error(`Input "past" third dimension must be num_heads`);if(o.dims[4]!==f/t.numHeads)throw Error(`Input "past" fifth dimension must be k_hidden_size / num_heads`);t.pastPresentShareBuffer||(h=o.dims[3])}let g=m+h;if(a)throw Error(`Mask not supported`);if(o)throw Error(`past is not supported`);if(s){if(s.dims.length!==4)throw Error(`Input "attention_bias" must have 4 dimensions`);if(s.dims[0]!==c||s.dims[1]!==t.numHeads||s.dims[2]!==l||s.dims[3]!==g)throw Error(`Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)`)}return{batchSize:c,sequenceLength:l,pastSequenceLength:h,kvSequenceLength:m,totalSequenceLength:g,maxSequenceLength:-1,inputHiddenSize:u,hiddenSize:d,vHiddenSize:p,headSize:Math.floor(d/t.numHeads),vHeadSize:Math.floor(p/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},pK=(e,t,n)=>t&&e?`
12988
12988
  let total_sequence_length_input = u32(${t.getByOffset(`0`)});
12989
12989
  let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
12990
12990
  let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
@@ -12997,7 +12997,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
12997
12997
  `:`
12998
12998
  ${n?`let past_sequence_length = uniforms.past_sequence_length`:``};
12999
12999
  let present_sequence_length = total_sequence_length;
13000
- `,fK=(e,t,n,r,i,a,o,s)=>{let c=HW(o?1:a),l=64,u=a/c;u<l&&(l=32);let d=Math.ceil(a/c/l),f=[{type:12,data:t},{type:12,data:n},{type:12,data:r},{type:12,data:i},{type:12,data:u},{type:12,data:d}],p=zW(e.dataType,c),m=BW(1,c),h=[`type`];return o&&h.push(`type`),s&&h.push(`type`),{name:`AttentionProbsSoftmax`,shaderCache:{hint:`${l};${p};${c}`,inputDependencies:h},getShaderSource:t=>{let n=JW(`x`,e.dataType,e.dims,c),r=[n],i=o?$(`seq_lens`,o.dataType,o.dims):void 0;i&&r.push(i);let a=s?$(`total_sequence_length_input`,s.dataType,s.dims):void 0;a&&r.push(a);let u=BW(e.dataType);return`
13000
+ `,mK=(e,t,n,r,i,a,o,s)=>{let c=WW(o?1:a),l=64,u=a/c;u<l&&(l=32);let d=Math.ceil(a/c/l),f=[{type:12,data:t},{type:12,data:n},{type:12,data:r},{type:12,data:i},{type:12,data:u},{type:12,data:d}],p=VW(e.dataType,c),m=HW(1,c),h=[`type`];return o&&h.push(`type`),s&&h.push(`type`),{name:`AttentionProbsSoftmax`,shaderCache:{hint:`${l};${p};${c}`,inputDependencies:h},getShaderSource:t=>{let n=XW(`x`,e.dataType,e.dims,c),r=[n],i=o?$(`seq_lens`,o.dataType,o.dims):void 0;i&&r.push(i);let a=s?$(`total_sequence_length_input`,s.dataType,s.dims):void 0;a&&r.push(a);let u=HW(e.dataType);return`
13001
13001
  var<workgroup> thread_max: array<f32, ${l}>;
13002
13002
  var<workgroup> thread_sum: array<f32, ${l}>;
13003
13003
  ${t.registerUniforms([{name:`batch_size`,type:`u32`},{name:`num_heads`,type:`u32`},{name:`past_sequence_length`,type:`u32`},{name:`sequence_length`,type:`u32`},{name:`total_sequence_length`,type:`u32`},{name:`elements_per_thread`,type:`u32`}]).declareVariables(...r)}
@@ -13006,7 +13006,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13006
13006
  let headIdx = workgroup_id.z % uniforms.num_heads;
13007
13007
  let sequence_length = uniforms.sequence_length;
13008
13008
  var total_sequence_length = uniforms.total_sequence_length;
13009
- ${dK(i,a,!1)}
13009
+ ${pK(i,a,!1)}
13010
13010
  let local_offset = local_idx * uniforms.elements_per_thread;
13011
13011
  let offset = (global_idx / ${l}) * uniforms.total_sequence_length + local_offset;
13012
13012
  let seq_causal_length = ${o?`u32(past_sequence_length + workgroup_id.y + 1)`:`total_sequence_length`};
@@ -13048,7 +13048,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13048
13048
  for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
13049
13049
  x[offset + total_seq_id] = ${n.type.value}(${u}(0));
13050
13050
  }`:``};
13051
- }`},getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:i,z:t*n},programUniforms:f})}},pK=(e,t,n,r,i,a,o,s,c)=>{let l=o+a.kvSequenceLength,u=[a.batchSize,a.numHeads,a.sequenceLength,l],d=e>1&&r,f=a.kvNumHeads?a.kvNumHeads:a.numHeads,p=d?[a.batchSize,f,l,a.headSize]:void 0,m=a.nReps?a.nReps:1,h=a.scale===0?1/Math.sqrt(a.headSize):a.scale,g=HW(a.headSize),_=a.headSize/g,v={x:Math.ceil(l/12),y:Math.ceil(a.sequenceLength/12),z:a.batchSize*a.numHeads},y=[{type:12,data:a.sequenceLength},{type:12,data:_},{type:12,data:l},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:h},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:m}],b=d&&r&&Q.size(r.dims)>0,x=[`type`,`type`];b&&x.push(`type`),i&&x.push(`type`),s&&x.push(`type`),c&&x.push(`type`);let S=[{dims:u,dataType:t.dataType,gpuDataType:0}];return d&&S.push({dims:p,dataType:t.dataType,gpuDataType:0}),{name:`AttentionProbs`,shaderCache:{hint:`${g};${i!==void 0};${r!==void 0};${e}`,inputDependencies:x},getRunData:()=>({outputs:S,dispatchGroup:v,programUniforms:y}),getShaderSource:e=>{let a=$(`q`,t.dataType,t.dims,g),o=[a,$(`key`,n.dataType,n.dims,g)];if(b){let e=$(`past_key`,r.dataType,r.dims,g);o.push(e)}i&&o.push($(`attention_bias`,i.dataType,i.dims));let l=s?$(`seq_lens`,s.dataType,s.dims):void 0;l&&o.push(l);let f=c?$(`total_sequence_length_input`,c.dataType,c.dims):void 0;f&&o.push(f);let h=JW(`output`,t.dataType,u),_=[h];d&&_.push(JW(`present_key`,t.dataType,p,g));let v=BW(1,g);return`
13051
+ }`},getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:i,z:t*n},programUniforms:f})}},hK=(e,t,n,r,i,a,o,s,c)=>{let l=o+a.kvSequenceLength,u=[a.batchSize,a.numHeads,a.sequenceLength,l],d=e>1&&r,f=a.kvNumHeads?a.kvNumHeads:a.numHeads,p=d?[a.batchSize,f,l,a.headSize]:void 0,m=a.nReps?a.nReps:1,h=a.scale===0?1/Math.sqrt(a.headSize):a.scale,g=WW(a.headSize),_=a.headSize/g,v={x:Math.ceil(l/12),y:Math.ceil(a.sequenceLength/12),z:a.batchSize*a.numHeads},y=[{type:12,data:a.sequenceLength},{type:12,data:_},{type:12,data:l},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:h},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:m}],b=d&&r&&Q.size(r.dims)>0,x=[`type`,`type`];b&&x.push(`type`),i&&x.push(`type`),s&&x.push(`type`),c&&x.push(`type`);let S=[{dims:u,dataType:t.dataType,gpuDataType:0}];return d&&S.push({dims:p,dataType:t.dataType,gpuDataType:0}),{name:`AttentionProbs`,shaderCache:{hint:`${g};${i!==void 0};${r!==void 0};${e}`,inputDependencies:x},getRunData:()=>({outputs:S,dispatchGroup:v,programUniforms:y}),getShaderSource:e=>{let a=$(`q`,t.dataType,t.dims,g),o=[a,$(`key`,n.dataType,n.dims,g)];if(b){let e=$(`past_key`,r.dataType,r.dims,g);o.push(e)}i&&o.push($(`attention_bias`,i.dataType,i.dims));let l=s?$(`seq_lens`,s.dataType,s.dims):void 0;l&&o.push(l);let f=c?$(`total_sequence_length_input`,c.dataType,c.dims):void 0;f&&o.push(f);let h=XW(`output`,t.dataType,u),_=[h];d&&_.push(XW(`present_key`,t.dataType,p,g));let v=HW(1,g);return`
13052
13052
  const TILE_SIZE = 12u;
13053
13053
 
13054
13054
  var<workgroup> tileQ: array<${a.type.storage}, 144>;
@@ -13064,7 +13064,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13064
13064
  let n = workgroup_id.x * TILE_SIZE;
13065
13065
  let sequence_length = uniforms.M;
13066
13066
  var total_sequence_length = uniforms.N;
13067
- ${dK(l,f,!0)}
13067
+ ${pK(l,f,!0)}
13068
13068
  let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
13069
13069
  let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
13070
13070
  ${b&&d?`let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;`:``};
@@ -13105,7 +13105,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13105
13105
  var sum: f32 = ${(()=>{switch(g){case 1:return`value`;case 2:return`value.x + value.y`;case 4:return`value.x + value.y + value.z + value.w`;default:throw Error(`Unsupported components: ${g}`)}})()};
13106
13106
  output[outputIdx] = ${h.type.value} (sum * uniforms.alpha) + ${i?`attention_bias[outputIdx]`:`0.0`};
13107
13107
  }
13108
- }`}}},mK=(e,t,n,r,i,a,o=void 0,s=void 0)=>{let c=a+i.kvSequenceLength,l=i.nReps?i.nReps:1,u=i.vHiddenSize*l,d=e>1&&r,f=i.kvNumHeads?i.kvNumHeads:i.numHeads,p=d?[i.batchSize,f,c,i.headSize]:void 0,m=[i.batchSize,i.sequenceLength,u],h={x:Math.ceil(i.vHeadSize/12),y:Math.ceil(i.sequenceLength/12),z:i.batchSize*i.numHeads},g=[{type:12,data:i.sequenceLength},{type:12,data:c},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:u},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:l}],_=d&&r&&Q.size(r.dims)>0,v=[`type`,`type`];_&&v.push(`type`),o&&v.push(`type`),s&&v.push(`type`);let y=[{dims:m,dataType:t.dataType,gpuDataType:0}];return d&&y.push({dims:p,dataType:t.dataType,gpuDataType:0}),{name:`AttentionScore`,shaderCache:{hint:`${r!==void 0};${e}`,inputDependencies:v},getRunData:()=>({outputs:y,dispatchGroup:h,programUniforms:g}),getShaderSource:e=>{let i=$(`probs`,t.dataType,t.dims),a=[i,$(`v`,n.dataType,n.dims)];_&&a.push($(`past_value`,r.dataType,r.dims));let c=o?$(`seq_lens`,o.dataType,o.dims):void 0;o&&a.push(c);let u=s?$(`total_sequence_length_input`,s.dataType,s.dims):void 0;s&&a.push(u);let f=[JW(`output`,t.dataType,m)];return d&&f.push(JW(`present_value`,t.dataType,p)),`
13108
+ }`}}},gK=(e,t,n,r,i,a,o=void 0,s=void 0)=>{let c=a+i.kvSequenceLength,l=i.nReps?i.nReps:1,u=i.vHiddenSize*l,d=e>1&&r,f=i.kvNumHeads?i.kvNumHeads:i.numHeads,p=d?[i.batchSize,f,c,i.headSize]:void 0,m=[i.batchSize,i.sequenceLength,u],h={x:Math.ceil(i.vHeadSize/12),y:Math.ceil(i.sequenceLength/12),z:i.batchSize*i.numHeads},g=[{type:12,data:i.sequenceLength},{type:12,data:c},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:u},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:l}],_=d&&r&&Q.size(r.dims)>0,v=[`type`,`type`];_&&v.push(`type`),o&&v.push(`type`),s&&v.push(`type`);let y=[{dims:m,dataType:t.dataType,gpuDataType:0}];return d&&y.push({dims:p,dataType:t.dataType,gpuDataType:0}),{name:`AttentionScore`,shaderCache:{hint:`${r!==void 0};${e}`,inputDependencies:v},getRunData:()=>({outputs:y,dispatchGroup:h,programUniforms:g}),getShaderSource:e=>{let i=$(`probs`,t.dataType,t.dims),a=[i,$(`v`,n.dataType,n.dims)];_&&a.push($(`past_value`,r.dataType,r.dims));let c=o?$(`seq_lens`,o.dataType,o.dims):void 0;o&&a.push(c);let u=s?$(`total_sequence_length_input`,s.dataType,s.dims):void 0;s&&a.push(u);let f=[XW(`output`,t.dataType,m)];return d&&f.push(XW(`present_value`,t.dataType,p)),`
13109
13109
  const TILE_SIZE = 12u;
13110
13110
  var<workgroup> tileQ: array<${i.type.value}, 144>;
13111
13111
  var<workgroup> tileV: array<${i.type.value}, 144>;
@@ -13119,7 +13119,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13119
13119
  let n = global_id.x;
13120
13120
  let sequence_length = uniforms.M;
13121
13121
  var total_sequence_length = uniforms.K;
13122
- ${dK(c,u,!0)}
13122
+ ${pK(c,u,!0)}
13123
13123
  let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
13124
13124
  let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
13125
13125
  ${_&&d?`let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;`:``};
@@ -13160,7 +13160,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13160
13160
  + headIdx * uniforms.N + n;
13161
13161
  output[outputIdx] = value;
13162
13162
  }
13163
- }`}}},hK=(e,t,n,r,i,a,o,s,c,l,u=void 0,d=void 0)=>{let f=Math.min(e.outputCount,1+ +!!o+ +!!s),p=f>1?l.pastSequenceLength:0,m=p+l.kvSequenceLength,h=c&&Q.size(c.dims)>0?c:void 0,g=[t,n];f>1&&o&&Q.size(o.dims)>0&&g.push(o),h&&g.push(h),u&&g.push(u),d&&g.push(d);let _=e.compute(pK(f,t,n,o,h,l,p,u,d),{inputs:g,outputs:f>1?[-1,1]:[-1]})[0];e.compute(fK(_,l.batchSize,l.numHeads,p,l.sequenceLength,m,u,d),{inputs:u&&d?[_,u,d]:[_],outputs:[]});let v=[_,r];f>1&&s&&Q.size(s.dims)>0&&v.push(s),u&&v.push(u),d&&v.push(d),e.compute(mK(f,_,r,s,l,p,u,d),{inputs:v,outputs:f>1?[0,2]:[0]})},gK=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],r=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,o={x:Math.ceil(t.headSize/12),y:Math.ceil(t.sequenceLength/12),z:t.batchSize*t.numHeads},s=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:r},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}];return e.compute({name:`AttentionPrepare`,shaderCache:{inputDependencies:[`type`,`type`,`type`]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:c}),getShaderSource:e=>{let t=JW(`output_q`,s[0].dataType,n),r=JW(`output_k`,s[0].dataType,n),i=JW(`output_v`,s[0].dataType,n),a=$(`input`,s[0].dataType,s[0].dims),o=$(`weight`,s[1].dataType,s[1].dims),c=$(`bias`,s[2].dataType,s[2].dims),l=a.type.storage;return`
13163
+ }`}}},_K=(e,t,n,r,i,a,o,s,c,l,u=void 0,d=void 0)=>{let f=Math.min(e.outputCount,1+ +!!o+ +!!s),p=f>1?l.pastSequenceLength:0,m=p+l.kvSequenceLength,h=c&&Q.size(c.dims)>0?c:void 0,g=[t,n];f>1&&o&&Q.size(o.dims)>0&&g.push(o),h&&g.push(h),u&&g.push(u),d&&g.push(d);let _=e.compute(hK(f,t,n,o,h,l,p,u,d),{inputs:g,outputs:f>1?[-1,1]:[-1]})[0];e.compute(mK(_,l.batchSize,l.numHeads,p,l.sequenceLength,m,u,d),{inputs:u&&d?[_,u,d]:[_],outputs:[]});let v=[_,r];f>1&&s&&Q.size(s.dims)>0&&v.push(s),u&&v.push(u),d&&v.push(d),e.compute(gK(f,_,r,s,l,p,u,d),{inputs:v,outputs:f>1?[0,2]:[0]})},vK=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],r=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,o={x:Math.ceil(t.headSize/12),y:Math.ceil(t.sequenceLength/12),z:t.batchSize*t.numHeads},s=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:r},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}];return e.compute({name:`AttentionPrepare`,shaderCache:{inputDependencies:[`type`,`type`,`type`]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:c}),getShaderSource:e=>{let t=XW(`output_q`,s[0].dataType,n),r=XW(`output_k`,s[0].dataType,n),i=XW(`output_v`,s[0].dataType,n),a=$(`input`,s[0].dataType,s[0].dims),o=$(`weight`,s[1].dataType,s[1].dims),c=$(`bias`,s[2].dataType,s[2].dims),l=a.type.storage;return`
13164
13164
  const TILE_SIZE = 12u;
13165
13165
  var<workgroup> tileInput: array<${l}, 144>;
13166
13166
  var<workgroup> tileWeightQ: array<${l}, 144>;
@@ -13215,7 +13215,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13215
13215
  output_k[outputIdx] = valueK;
13216
13216
  output_v[outputIdx] = valueV;
13217
13217
  }
13218
- }`}},{inputs:s,outputs:[-1,-1,-1]})},_K=(e,t)=>{let n=uK(e.inputs,t),[r,i,a]=gK(e,n);return hK(e,r,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),yK,bK,xK,SK,CK=Z(()=>{LH(),VU(),iW(),IW(),$W(),yK=(e,t)=>{if(!e||e.length!==5)throw Error(`BatchNormalization requires 5 inputs`);let n=(e,t,n)=>{let r=t.length;if(r!==e.length)throw Error(`${n}: num dimensions != ${r}`);t.forEach((t,r)=>{if(t!==e[r])throw Error(`${n}: dim[${r}] do not match`)})};if(e[0].dims.length>1){let r=t.format===`NHWC`?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,r,`Invalid input scale`),n(e[2].dims,r,`Invalid input B`),n(e[3].dims,r,`Invalid input mean`),n(e[4].dims,r,`Invalid input var`)}else n(e[1].dims,[1],`Invalid input scale`),n(e[2].dims,[1],`Invalid input B`),n(e[3].dims,[1],`Invalid input mean`),n(e[4].dims,[1],`Invalid input var`)},bK=(e,t)=>{let{epsilon:n,spatial:r,format:i}=t,a=e[0].dims,o=r?HW(a[a.length-1]):1,s=i===`NHWC`&&a.length>1?o:1,c=Q.size(a)/o,l=r,u=l?a.length:a,d=$(`x`,e[0].dataType,e[0].dims,o),f=$(`scale`,e[1].dataType,e[1].dims,s),p=$(`bias`,e[2].dataType,e[2].dims,s),m=$(`inputMean`,e[3].dataType,e[3].dims,s),h=$(`inputVar`,e[4].dataType,e[4].dims,s),g=JW(`y`,e[0].dataType,u,o),_=()=>{let e=``;if(r)e=`let cOffset = ${a.length===1?`0u`:i===`NHWC`?`outputIndices[${a.length-1}] / ${o}`:`outputIndices[1]`};`;else if(i===`NCHW`)e=`
13218
+ }`}},{inputs:s,outputs:[-1,-1,-1]})},yK=(e,t)=>{let n=fK(e.inputs,t),[r,i,a]=vK(e,n);return _K(e,r,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),xK,SK,CK,wK,TK=Z(()=>{zH(),UU(),oW(),RW(),tG(),xK=(e,t)=>{if(!e||e.length!==5)throw Error(`BatchNormalization requires 5 inputs`);let n=(e,t,n)=>{let r=t.length;if(r!==e.length)throw Error(`${n}: num dimensions != ${r}`);t.forEach((t,r)=>{if(t!==e[r])throw Error(`${n}: dim[${r}] do not match`)})};if(e[0].dims.length>1){let r=t.format===`NHWC`?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,r,`Invalid input scale`),n(e[2].dims,r,`Invalid input B`),n(e[3].dims,r,`Invalid input mean`),n(e[4].dims,r,`Invalid input var`)}else n(e[1].dims,[1],`Invalid input scale`),n(e[2].dims,[1],`Invalid input B`),n(e[3].dims,[1],`Invalid input mean`),n(e[4].dims,[1],`Invalid input var`)},SK=(e,t)=>{let{epsilon:n,spatial:r,format:i}=t,a=e[0].dims,o=r?WW(a[a.length-1]):1,s=i===`NHWC`&&a.length>1?o:1,c=Q.size(a)/o,l=r,u=l?a.length:a,d=$(`x`,e[0].dataType,e[0].dims,o),f=$(`scale`,e[1].dataType,e[1].dims,s),p=$(`bias`,e[2].dataType,e[2].dims,s),m=$(`inputMean`,e[3].dataType,e[3].dims,s),h=$(`inputVar`,e[4].dataType,e[4].dims,s),g=XW(`y`,e[0].dataType,u,o),_=()=>{let e=``;if(r)e=`let cOffset = ${a.length===1?`0u`:i===`NHWC`?`outputIndices[${a.length-1}] / ${o}`:`outputIndices[1]`};`;else if(i===`NCHW`)e=`
13219
13219
  ${g.indicesSet(`outputIndices`,`0`,`0`)}
13220
13220
  let cOffset = ${g.indicesToOffset(`outputIndices`)};`;else{e=`var cIndices = ${f.type.indices}(0);
13221
13221
  cIndices[0] = outputIndices[${a.length-1}];`;for(let t=1;t<f.rank;t++)e+=`cIndices[${t}] = outputIndices[${t}];`;e+=`let cOffset = ${f.indicesToOffset(`cIndices`)};`}return e};return{name:`BatchNormalization`,shaderCache:{hint:`${t.epsilon}_${t.format}_${r}_${o}`,inputDependencies:l?[`rank`,`type`,`type`,`type`,`type`]:void 0},getShaderSource:e=>`
@@ -13232,7 +13232,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13232
13232
  let x = ${d.getByOffset(`global_idx`)};
13233
13233
  let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
13234
13234
  ${g.setByOffset(`global_idx`,`value`)}
13235
- }`,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:l?[{type:12,data:c},...VW(a)]:[{type:12,data:c}]})}},xK=e=>FW(e),SK=(e,t)=>{let{inputs:n,outputCount:r}=e,i=xK({...t,outputCount:r});if(QV.webgpu.validateInputContent&&yK(n,i),t.trainingMode)throw Error(`BatchNormalization trainingMode is not supported yet.`);e.compute(bK(n,i))}}),wK,TK,EK,DK=Z(()=>{iW(),$W(),wK=e=>{if(e[0].dims.length!==3)throw Error(`input should have 3 dimensions`);if(![320,640,1280].includes(e[0].dims[2]))throw Error(`number of channels should be 320, 640 or 1280`);if(e[1].dims.length!==1)throw Error(`bias is expected to have 1 dimensions`);if(e[0].dims[2]!==e[1].dims[0])throw Error(`last dimension of input and bias are not the same`)},TK=e=>{let t=e[0].dims,n=e[0].dims[2],r=Q.size(t)/4,i=e[0].dataType,a=$(`input`,i,t,4),o=$(`bias`,i,[n],4),s=$(`residual`,i,t,4),c=JW(`output`,i,t,4);return{name:`BiasAdd`,getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:e=>`
13235
+ }`,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:l?[{type:12,data:c},...UW(a)]:[{type:12,data:c}]})}},CK=e=>LW(e),wK=(e,t)=>{let{inputs:n,outputCount:r}=e,i=CK({...t,outputCount:r});if(eH.webgpu.validateInputContent&&xK(n,i),t.trainingMode)throw Error(`BatchNormalization trainingMode is not supported yet.`);e.compute(SK(n,i))}}),EK,DK,OK,kK=Z(()=>{oW(),tG(),EK=e=>{if(e[0].dims.length!==3)throw Error(`input should have 3 dimensions`);if(![320,640,1280].includes(e[0].dims[2]))throw Error(`number of channels should be 320, 640 or 1280`);if(e[1].dims.length!==1)throw Error(`bias is expected to have 1 dimensions`);if(e[0].dims[2]!==e[1].dims[0])throw Error(`last dimension of input and bias are not the same`)},DK=e=>{let t=e[0].dims,n=e[0].dims[2],r=Q.size(t)/4,i=e[0].dataType,a=$(`input`,i,t,4),o=$(`bias`,i,[n],4),s=$(`residual`,i,t,4),c=XW(`output`,i,t,4);return{name:`BiasAdd`,getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:e=>`
13236
13236
  const channels = ${n}u / 4;
13237
13237
  ${e.declareVariables(a,o,s,c)}
13238
13238
 
@@ -13241,7 +13241,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13241
13241
  let value = ${a.getByOffset(`global_idx`)}
13242
13242
  + ${o.getByOffset(`global_idx % channels`)} + ${s.getByOffset(`global_idx`)};
13243
13243
  ${c.setByOffset(`global_idx`,`value`)}
13244
- }`}},EK=e=>{wK(e.inputs),e.compute(TK(e.inputs))}}),OK,kK,AK,jK,MK,NK,PK,FK,IK,LK,RK,zK,BK,VK,HK,UK,WK,GK,KK,qK,JK,YK,XK,ZK,QK,$K,eq,tq,nq,rq,iq,aq,oq,sq,cq,lq,uq,dq,fq,pq,mq,hq,gq,_q,vq,yq=Z(()=>{VU(),iW(),IW(),$W(),OK=(e,t,n,r,i,a,o)=>{let s=Math.ceil(t/4),c=``;c=typeof i==`string`?`${i}(a)`:i(`a`);let l=$(`inputData`,n,[s],4),u=JW(`outputData`,r,[s],4),d=[{name:`vec_size`,type:`u32`}];return o&&d.push(...o),`
13244
+ }`}},OK=e=>{EK(e.inputs),e.compute(DK(e.inputs))}}),AK,jK,MK,NK,PK,FK,IK,LK,RK,zK,BK,VK,HK,UK,WK,GK,KK,qK,JK,YK,XK,ZK,QK,$K,eq,tq,nq,rq,iq,aq,oq,sq,cq,lq,uq,dq,fq,pq,mq,hq,gq,_q,vq,yq,bq,xq=Z(()=>{UU(),oW(),RW(),tG(),AK=(e,t,n,r,i,a,o)=>{let s=Math.ceil(t/4),c=``;c=typeof i==`string`?`${i}(a)`:i(`a`);let l=$(`inputData`,n,[s],4),u=XW(`outputData`,r,[s],4),d=[{name:`vec_size`,type:`u32`}];return o&&d.push(...o),`
13245
13245
  ${e.registerUniforms(d).declareVariables(l,u)}
13246
13246
 
13247
13247
  ${a??``}
@@ -13251,7 +13251,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13251
13251
 
13252
13252
  let a = ${l.getByOffset(`global_idx`)};
13253
13253
  ${u.setByOffset(`global_idx`,c)}
13254
- }`},kK=(e,t,n,r,i,a=e.dataType,o,s)=>{let c=[{type:12,data:Math.ceil(Q.size(e.dims)/4)}];return o&&c.push(...o),{name:t,shaderCache:{hint:i,inputDependencies:[`type`]},getShaderSource:t=>OK(t,Q.size(e.dims),e.dataType,a,n,r,s),getRunData:t=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Q.size(t[0].dims)/64/4)},programUniforms:c})}},AK=e=>{e.compute(kK(e.inputs[0],`Abs`,`abs`))},jK=e=>{e.compute(kK(e.inputs[0],`Acos`,`acos`))},MK=e=>{e.compute(kK(e.inputs[0],`Acosh`,`acosh`))},NK=e=>{e.compute(kK(e.inputs[0],`Asin`,`asin`))},PK=e=>{e.compute(kK(e.inputs[0],`Asinh`,`asinh`))},FK=e=>{e.compute(kK(e.inputs[0],`Atan`,`atan`))},IK=e=>{e.compute(kK(e.inputs[0],`Atanh`,`atanh`))},LK=e=>FW(e),RK=(e,t)=>{let n;switch(t.to){case 10:n=`vec4<f16>`;break;case 1:n=`vec4<f32>`;break;case 12:n=`vec4<u32>`;break;case 6:n=`vec4<i32>`;break;case 9:n=`vec4<bool>`;break;default:throw RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(kK(e.inputs[0],`Cast`,n,void 0,t.cacheKey,t.to))},zK=e=>{let t,n,r=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=r?e[1].getFloat32Array()[0]:-34028234663852886e22,n=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=r?e[1].getUint16Array()[0]:64511,n=i?e[2].getUint16Array()[0]:31743;break;default:throw Error(`Unsupport data type`)}return FW({min:t,max:n})},BK=(e,t)=>{let n=t||zK(e.inputs),r=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`Clip`,e=>`clamp(${e}, vec4<${r}>(uniforms.min), vec4<${r}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:`min`,type:r},{name:`max`,type:r}]),{inputs:[0]})},VK=e=>{e.compute(kK(e.inputs[0],`Ceil`,`ceil`))},HK=e=>{e.compute(kK(e.inputs[0],`Cos`,`cos`))},UK=e=>{e.compute(kK(e.inputs[0],`Cosh`,`cosh`))},WK=e=>FW(e),GK=(e,t)=>{let n=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`Elu`,e=>`elu_vf32(${e})`,`
13254
+ }`},jK=(e,t,n,r,i,a=e.dataType,o,s)=>{let c=[{type:12,data:Math.ceil(Q.size(e.dims)/4)}];return o&&c.push(...o),{name:t,shaderCache:{hint:i,inputDependencies:[`type`]},getShaderSource:t=>AK(t,Q.size(e.dims),e.dataType,a,n,r,s),getRunData:t=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Q.size(t[0].dims)/64/4)},programUniforms:c})}},MK=e=>{e.compute(jK(e.inputs[0],`Abs`,`abs`))},NK=e=>{e.compute(jK(e.inputs[0],`Acos`,`acos`))},PK=e=>{e.compute(jK(e.inputs[0],`Acosh`,`acosh`))},FK=e=>{e.compute(jK(e.inputs[0],`Asin`,`asin`))},IK=e=>{e.compute(jK(e.inputs[0],`Asinh`,`asinh`))},LK=e=>{e.compute(jK(e.inputs[0],`Atan`,`atan`))},RK=e=>{e.compute(jK(e.inputs[0],`Atanh`,`atanh`))},zK=e=>LW(e),BK=(e,t)=>{let n;switch(t.to){case 10:n=`vec4<f16>`;break;case 1:n=`vec4<f32>`;break;case 12:n=`vec4<u32>`;break;case 6:n=`vec4<i32>`;break;case 9:n=`vec4<bool>`;break;default:throw RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(jK(e.inputs[0],`Cast`,n,void 0,t.cacheKey,t.to))},VK=e=>{let t,n,r=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=r?e[1].getFloat32Array()[0]:-34028234663852886e22,n=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=r?e[1].getUint16Array()[0]:64511,n=i?e[2].getUint16Array()[0]:31743;break;default:throw Error(`Unsupport data type`)}return LW({min:t,max:n})},HK=(e,t)=>{let n=t||VK(e.inputs),r=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`Clip`,e=>`clamp(${e}, vec4<${r}>(uniforms.min), vec4<${r}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:`min`,type:r},{name:`max`,type:r}]),{inputs:[0]})},UK=e=>{e.compute(jK(e.inputs[0],`Ceil`,`ceil`))},WK=e=>{e.compute(jK(e.inputs[0],`Cos`,`cos`))},GK=e=>{e.compute(jK(e.inputs[0],`Cosh`,`cosh`))},KK=e=>LW(e),qK=(e,t)=>{let n=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`Elu`,e=>`elu_vf32(${e})`,`
13255
13255
  const elu_alpha_ = ${n}(${t.alpha});
13256
13256
 
13257
13257
  fn elu_f32(a: ${n}) -> ${n} {
@@ -13260,7 +13260,7 @@ var best_index : i32 = 0;`,`if (${e.getByIndices(`input_indices`)} ${t.selectLas
13260
13260
 
13261
13261
  fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {
13262
13262
  return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
13263
- }`,t.cacheKey))},KK=(e=`f32`)=>`
13263
+ }`,t.cacheKey))},JK=(e=`f32`)=>`
13264
13264
  const r0: ${e} = 0.3275911;
13265
13265
  const r1: ${e} = 0.254829592;
13266
13266
  const r2: ${e} = -0.284496736;
@@ -13272,15 +13272,15 @@ fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
13272
13272
  let absv = abs(v);
13273
13273
  let x = 1.0 / (1.0 + r0 * absv);
13274
13274
  return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
13275
- }`,qK=e=>{let t=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`Erf`,e=>`erf_vf32(${e})`,KK(t)))},JK=e=>{e.compute(kK(e.inputs[0],`Exp`,`exp`))},YK=e=>{e.compute(kK(e.inputs[0],`Floor`,`floor`))},XK=e=>{let t=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`Gelu`,e=>`0.5 * ${e} * (1.0 + erf_vf32(${e} * 0.7071067811865475))`,KK(t)))},ZK=(e,t)=>{let n=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`LeakyRelu`,e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},QK=e=>{e.compute(kK(e.inputs[0],`Not`,e=>`!${e}`))},$K=e=>{e.compute(kK(e.inputs[0],`Neg`,e=>`-${e}`))},eq=e=>{e.compute(kK(e.inputs[0],`Reciprocal`,e=>`1.0/${e}`))},tq=e=>{let t=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`Relu`,e=>`select(vec4<${t}>(0.0), ${e}, ${e} > vec4<${t}>(0.0))`))},nq=e=>{e.compute(kK(e.inputs[0],`Sigmoid`,e=>`(1.0 / (1.0 + exp(-${e})))`))},rq=e=>FW(e),iq=(e,t)=>{let n=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`HardSigmoid`,e=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${e} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},aq=e=>{e.compute(kK(e.inputs[0],`Sin`,`sin`))},oq=e=>{e.compute(kK(e.inputs[0],`Sinh`,`sinh`))},sq=e=>{e.compute(kK(e.inputs[0],`Sqrt`,`sqrt`))},cq=e=>{e.compute(kK(e.inputs[0],`Tan`,`tan`))},lq=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,uq=e=>{e.compute(kK(e.inputs[0],`Tanh`,lq))},dq=(e=`f32`)=>`
13275
+ }`,YK=e=>{let t=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`Erf`,e=>`erf_vf32(${e})`,JK(t)))},XK=e=>{e.compute(jK(e.inputs[0],`Exp`,`exp`))},ZK=e=>{e.compute(jK(e.inputs[0],`Floor`,`floor`))},QK=e=>{let t=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`Gelu`,e=>`0.5 * ${e} * (1.0 + erf_vf32(${e} * 0.7071067811865475))`,JK(t)))},$K=(e,t)=>{let n=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`LeakyRelu`,e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},eq=e=>{e.compute(jK(e.inputs[0],`Not`,e=>`!${e}`))},tq=e=>{e.compute(jK(e.inputs[0],`Neg`,e=>`-${e}`))},nq=e=>{e.compute(jK(e.inputs[0],`Reciprocal`,e=>`1.0/${e}`))},rq=e=>{let t=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`Relu`,e=>`select(vec4<${t}>(0.0), ${e}, ${e} > vec4<${t}>(0.0))`))},iq=e=>{e.compute(jK(e.inputs[0],`Sigmoid`,e=>`(1.0 / (1.0 + exp(-${e})))`))},aq=e=>LW(e),oq=(e,t)=>{let n=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`HardSigmoid`,e=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${e} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},sq=e=>{e.compute(jK(e.inputs[0],`Sin`,`sin`))},cq=e=>{e.compute(jK(e.inputs[0],`Sinh`,`sinh`))},lq=e=>{e.compute(jK(e.inputs[0],`Sqrt`,`sqrt`))},uq=e=>{e.compute(jK(e.inputs[0],`Tan`,`tan`))},dq=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,fq=e=>{e.compute(jK(e.inputs[0],`Tanh`,dq))},pq=(e=`f32`)=>`
13276
13276
  const fast_gelu_a: ${e} = 0.5;
13277
13277
  const fast_gelu_b: ${e} = 0.7978845608028654;
13278
13278
  const fast_gelu_c: ${e} = 0.035677408136300125;
13279
13279
 
13280
13280
  fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
13281
- return ${lq(`v`)};
13281
+ return ${dq(`v`)};
13282
13282
  }
13283
- `,fq=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,pq=e=>{let t=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`FastGelu`,fq,dq(t),void 0,e.inputs[0].dataType))},mq=(e,t)=>{let n=BW(e.inputs[0].dataType);return e.compute(kK(e.inputs[0],`ThresholdedRelu`,e=>`select(vec4<${n}>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},hq=e=>{e.compute(kK(e.inputs[0],`Log`,`log`))},gq=(e,t)=>`
13283
+ `,mq=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,hq=e=>{let t=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`FastGelu`,mq,pq(t),void 0,e.inputs[0].dataType))},gq=(e,t)=>{let n=HW(e.inputs[0].dataType);return e.compute(jK(e.inputs[0],`ThresholdedRelu`,e=>`select(vec4<${n}>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},_q=e=>{e.compute(jK(e.inputs[0],`Log`,`log`))},vq=(e,t)=>`
13284
13284
  const alpha = vec4<${e}>(${t});
13285
13285
  const one = ${e}(1.0);
13286
13286
  const zero = ${e}(0.0);
@@ -13297,13 +13297,13 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
13297
13297
  }
13298
13298
  return x * x1;
13299
13299
  }
13300
- `,_q=e=>`quick_gelu_impl(${e})`,vq=(e,t)=>{let n=BW(e.inputs[0].dataType);e.compute(kK(e.inputs[0],`QuickGelu`,_q,gq(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),bq,xq,Sq,Cq=Z(()=>{iW(),$W(),yq(),bq=e=>{if(e[0].dims.length!==3)throw Error(`input should have 3 dimensions`);if(![2560,5120,10240].includes(e[0].dims[2]))throw Error(`hidden state should be 2560, 5120 or 10240`);if(e[1].dims.length!==1)throw Error(`bias is expected to have 1 dimensions`);if(e[0].dims[2]!==e[1].dims[0])throw Error(`last dimension of input and bias are not the same`)},xq=e=>{let t=e[0].dims.slice();t[2]/=2;let n=$(`input`,e[0].dataType,e[0].dims,4),r=$(`bias`,e[0].dataType,[e[0].dims[2]],4),i=JW(`output`,e[0].dataType,t,4),a=Q.size(t)/4,o=zW(e[0].dataType);return{name:`BiasSplitGelu`,getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:t=>`
13300
+ `,yq=e=>`quick_gelu_impl(${e})`,bq=(e,t)=>{let n=HW(e.inputs[0].dataType);e.compute(jK(e.inputs[0],`QuickGelu`,yq,vq(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Sq,Cq,wq,Tq=Z(()=>{oW(),tG(),xq(),Sq=e=>{if(e[0].dims.length!==3)throw Error(`input should have 3 dimensions`);if(![2560,5120,10240].includes(e[0].dims[2]))throw Error(`hidden state should be 2560, 5120 or 10240`);if(e[1].dims.length!==1)throw Error(`bias is expected to have 1 dimensions`);if(e[0].dims[2]!==e[1].dims[0])throw Error(`last dimension of input and bias are not the same`)},Cq=e=>{let t=e[0].dims.slice();t[2]/=2;let n=$(`input`,e[0].dataType,e[0].dims,4),r=$(`bias`,e[0].dataType,[e[0].dims[2]],4),i=XW(`output`,e[0].dataType,t,4),a=Q.size(t)/4,o=VW(e[0].dataType);return{name:`BiasSplitGelu`,getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:t=>`
13301
13301
  const M_SQRT2 = sqrt(2.0);
13302
13302
  const halfChannels = ${e[0].dims[2]/4/2}u;
13303
13303
 
13304
13304
  ${t.declareVariables(n,r,i)}
13305
13305
 
13306
- ${KK(o)}
13306
+ ${JK(o)}
13307
13307
 
13308
13308
  ${t.mainStart()}
13309
13309
  ${t.guardAgainstOutOfBoundsWorkgroupSizes(a)}
@@ -13315,7 +13315,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
13315
13315
  let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
13316
13316
 
13317
13317
  ${i.setByOffset(`global_idx`,`valueLeft * geluRight`)}
13318
- }`}},Sq=e=>{bq(e.inputs),e.compute(xq(e.inputs))}}),wq,Tq,Eq,Dq,Oq,kq,Aq,jq,Mq,Nq,Pq,Fq,Iq,Lq=Z(()=>{VU(),iW(),$W(),wq=(e,t,n,r,i,a,o,s,c,l,u,d)=>{let f,p;typeof s==`string`?f=p=(e,t)=>`${s}((${e}),(${t}))`:typeof s==`function`?f=p=s:(f=s.scalar,p=s.vector);let m=JW(`outputData`,u,r.length,4),h=$(`aData`,c,t.length,4),g=$(`bData`,l,n.length,4),_;if(i)if(a){let e=Q.size(t)===1,r=Q.size(n)===1,i=t.length>0&&t[t.length-1]%4==0,a=n.length>0&&n[n.length-1]%4==0;_=e||r?m.setByOffset(`global_idx`,p(e?`${h.type.value}(${h.getByOffset(`0`)}.x)`:h.getByOffset(`global_idx`),r?`${g.type.value}(${g.getByOffset(`0`)}.x)`:g.getByOffset(`global_idx`))):`
13318
+ }`}},wq=e=>{Sq(e.inputs),e.compute(Cq(e.inputs))}}),Eq,Dq,Oq,kq,Aq,jq,Mq,Nq,Pq,Fq,Iq,Lq,Rq,zq=Z(()=>{UU(),oW(),tG(),Eq=(e,t,n,r,i,a,o,s,c,l,u,d)=>{let f,p;typeof s==`string`?f=p=(e,t)=>`${s}((${e}),(${t}))`:typeof s==`function`?f=p=s:(f=s.scalar,p=s.vector);let m=XW(`outputData`,u,r.length,4),h=$(`aData`,c,t.length,4),g=$(`bData`,l,n.length,4),_;if(i)if(a){let e=Q.size(t)===1,r=Q.size(n)===1,i=t.length>0&&t[t.length-1]%4==0,a=n.length>0&&n[n.length-1]%4==0;_=e||r?m.setByOffset(`global_idx`,p(e?`${h.type.value}(${h.getByOffset(`0`)}.x)`:h.getByOffset(`global_idx`),r?`${g.type.value}(${g.getByOffset(`0`)}.x)`:g.getByOffset(`global_idx`))):`
13319
13319
  let outputIndices = ${m.offsetToIndices(`global_idx * 4u`)};
13320
13320
  let offsetA = ${h.broadcastedIndicesToOffset(`outputIndices`,m)};
13321
13321
  let offsetB = ${g.broadcastedIndicesToOffset(`outputIndices`,m)};
@@ -13348,7 +13348,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
13348
13348
  ${e.mainStart()}
13349
13349
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.vec_size`)}
13350
13350
  ${_}
13351
- }`},Tq=(e,t,n,r,i,a,o=n.dataType)=>{let s=n.dims.map(Number),c=r.dims.map(Number),l=!Q.areEqual(s,c),u=s,d=Q.size(s),f=!1,p=!1,m=[l];if(l){let e=$U.calcShape(s,c,!1);if(!e)throw Error(`Can't perform binary op on the given tensors`);u=e.slice(),d=Q.size(u);let t=Q.size(s)===1,n=Q.size(c)===1,r=s.length>0&&s[s.length-1]%4==0,i=c.length>0&&c[c.length-1]%4==0;m.push(t),m.push(n),m.push(r),m.push(i);let a=1;for(let e=1;e<u.length;e++){let t=s[s.length-e];if(t===c[c.length-e])a*=t;else break}a%4==0?(p=!0,f=!0):(t||n||r||i)&&(f=!0)}else f=!0;return m.push(f),{name:e,shaderCache:{hint:t+m.map(e=>e.toString()).join(`_`),inputDependencies:[`rank`,`rank`]},getShaderSource:e=>wq(e,s,c,u,f,l,p,i,n.dataType,r.dataType,o,a),getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(Q.size(u)/4)},...VW(s,c,u)]})}},Eq=(e,t,n,r,i,a)=>{e.compute(Tq(t,i??``,e.inputs[0],e.inputs[1],n,r,a))},Dq=e=>{Eq(e,`Add`,(e,t)=>`${e}+${t}`)},Oq=e=>{Eq(e,`Div`,(e,t)=>`${e}/${t}`)},kq=e=>{Eq(e,`Equal`,{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4<u32>(${e}==${t})`},void 0,void 0,9)},Aq=e=>{Eq(e,`Mul`,(e,t)=>`${e}*${t}`)},jq=e=>{let t=$(`input`,e.inputs[0].dataType,e.inputs[0].dims).type.value;Eq(e,`Pow`,{scalar:(e,t)=>`pow_custom(${e},${t})`,vector:(e,t)=>`pow_vector_custom(${e},${t})`},`
13351
+ }`},Dq=(e,t,n,r,i,a,o=n.dataType)=>{let s=n.dims.map(Number),c=r.dims.map(Number),l=!Q.areEqual(s,c),u=s,d=Q.size(s),f=!1,p=!1,m=[l];if(l){let e=tW.calcShape(s,c,!1);if(!e)throw Error(`Can't perform binary op on the given tensors`);u=e.slice(),d=Q.size(u);let t=Q.size(s)===1,n=Q.size(c)===1,r=s.length>0&&s[s.length-1]%4==0,i=c.length>0&&c[c.length-1]%4==0;m.push(t),m.push(n),m.push(r),m.push(i);let a=1;for(let e=1;e<u.length;e++){let t=s[s.length-e];if(t===c[c.length-e])a*=t;else break}a%4==0?(p=!0,f=!0):(t||n||r||i)&&(f=!0)}else f=!0;return m.push(f),{name:e,shaderCache:{hint:t+m.map(e=>e.toString()).join(`_`),inputDependencies:[`rank`,`rank`]},getShaderSource:e=>Eq(e,s,c,u,f,l,p,i,n.dataType,r.dataType,o,a),getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(Q.size(u)/4)},...UW(s,c,u)]})}},Oq=(e,t,n,r,i,a)=>{e.compute(Dq(t,i??``,e.inputs[0],e.inputs[1],n,r,a))},kq=e=>{Oq(e,`Add`,(e,t)=>`${e}+${t}`)},Aq=e=>{Oq(e,`Div`,(e,t)=>`${e}/${t}`)},jq=e=>{Oq(e,`Equal`,{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4<u32>(${e}==${t})`},void 0,void 0,9)},Mq=e=>{Oq(e,`Mul`,(e,t)=>`${e}*${t}`)},Nq=e=>{let t=$(`input`,e.inputs[0].dataType,e.inputs[0].dims).type.value;Oq(e,`Pow`,{scalar:(e,t)=>`pow_custom(${e},${t})`,vector:(e,t)=>`pow_vector_custom(${e},${t})`},`
13352
13352
  fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
13353
13353
  if (b == ${t}(0.0)) {
13354
13354
  return ${t}(1.0);
@@ -13361,7 +13361,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
13361
13361
  // TODO: implement vectorized pow
13362
13362
  return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
13363
13363
  }
13364
- `)},Mq=e=>{Eq(e,`Sub`,(e,t)=>`${e}-${t}`)},Nq=e=>{Eq(e,`Greater`,{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4<u32>(${e}>${t})`},void 0,void 0,9)},Pq=e=>{Eq(e,`Less`,{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4<u32>(${e}<${t})`},void 0,void 0,9)},Fq=e=>{Eq(e,`GreaterOrEqual`,{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4<u32>(${e}>=${t})`},void 0,void 0,9)},Iq=e=>{Eq(e,`LessOrEqual`,{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4<u32>(${e}<=${t})`},void 0,void 0,9)}}),Rq,zq,Bq,Vq,Hq,Uq,Wq=Z(()=>{VU(),iW(),IW(),$W(),Rq=(e,t)=>{if(!e||e.length<1)throw Error(`too few inputs`);let n=e[0],r=n.dataType,i=n.dims.length;e.forEach((e,a)=>{if(a!==0){if(e.dataType!==r)throw Error(`input tensors should be one type`);if(e.dims.length!==i)throw Error(`input tensors should have the same shape`);e.dims.forEach((e,r)=>{if(r!==t&&e!==n.dims[r])throw Error(`non concat dimensions must match`)})}})},zq=(e,t)=>`
13364
+ `)},Pq=e=>{Oq(e,`Sub`,(e,t)=>`${e}-${t}`)},Fq=e=>{Oq(e,`Greater`,{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4<u32>(${e}>${t})`},void 0,void 0,9)},Iq=e=>{Oq(e,`Less`,{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4<u32>(${e}<${t})`},void 0,void 0,9)},Lq=e=>{Oq(e,`GreaterOrEqual`,{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4<u32>(${e}>=${t})`},void 0,void 0,9)},Rq=e=>{Oq(e,`LessOrEqual`,{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4<u32>(${e}<=${t})`},void 0,void 0,9)}}),Bq,Vq,Hq,Uq,Wq,Gq,Kq=Z(()=>{UU(),oW(),RW(),tG(),Bq=(e,t)=>{if(!e||e.length<1)throw Error(`too few inputs`);let n=e[0],r=n.dataType,i=n.dims.length;e.forEach((e,a)=>{if(a!==0){if(e.dataType!==r)throw Error(`input tensors should be one type`);if(e.dims.length!==i)throw Error(`input tensors should have the same shape`);e.dims.forEach((e,r)=>{if(r!==t&&e!==n.dims[r])throw Error(`non concat dimensions must match`)})}})},Vq=(e,t)=>`
13365
13365
  fn calculateInputIndex(index: u32) -> u32 {
13366
13366
  let sizeInConcatAxis = array<u32, ${e}u>(${t});
13367
13367
  for (var i: u32 = 0u; i < ${e}; i += 1u ) {
@@ -13370,12 +13370,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
13370
13370
  }
13371
13371
  }
13372
13372
  return ${e}u;
13373
- }`,Bq=(e,t)=>{let n=e.length,r=[];for(let i=0;i<n;++i){let a=t.setByOffset(`global_idx`,e[i].getByIndices(`indices`));n===1?r.push(a):i===0?r.push(`if (inputIndex == ${i}u) { ${a} }`):i===n-1?r.push(`else { ${a} }`):r.push(`else if (inputIndex == ${i}) { ${a} }`)}return r.join(`
13374
- `)},Vq=(e,t,n,r)=>{let i=Q.size(n),a=Array(e.length),o=Array(e.length),s=0,c=[],l=[],u=[{type:12,data:i}];for(let n=0;n<e.length;++n)s+=e[n].dims[t],a[n]=s,l.push(e[n].dims.length),o[n]=$(`input${n}`,r,l[n]),c.push(`rank`),u.push({type:12,data:a[n]});for(let t=0;t<e.length;++t)u.push(...VW(e[t].dims));u.push(...VW(n));let d=JW(`output`,r,n.length),f=d.indicesGet(`indices`,t),p=Array.from(Array(a.length).keys()).map(e=>`uniforms.sizeInConcatAxis${e}`).join(`,`);return{name:`Concat`,shaderCache:{hint:`${t}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u}),getShaderSource:t=>`
13373
+ }`,Hq=(e,t)=>{let n=e.length,r=[];for(let i=0;i<n;++i){let a=t.setByOffset(`global_idx`,e[i].getByIndices(`indices`));n===1?r.push(a):i===0?r.push(`if (inputIndex == ${i}u) { ${a} }`):i===n-1?r.push(`else { ${a} }`):r.push(`else if (inputIndex == ${i}) { ${a} }`)}return r.join(`
13374
+ `)},Uq=(e,t,n,r)=>{let i=Q.size(n),a=Array(e.length),o=Array(e.length),s=0,c=[],l=[],u=[{type:12,data:i}];for(let n=0;n<e.length;++n)s+=e[n].dims[t],a[n]=s,l.push(e[n].dims.length),o[n]=$(`input${n}`,r,l[n]),c.push(`rank`),u.push({type:12,data:a[n]});for(let t=0;t<e.length;++t)u.push(...UW(e[t].dims));u.push(...UW(n));let d=XW(`output`,r,n.length),f=d.indicesGet(`indices`,t),p=Array.from(Array(a.length).keys()).map(e=>`uniforms.sizeInConcatAxis${e}`).join(`,`);return{name:`Concat`,shaderCache:{hint:`${t}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u}),getShaderSource:t=>`
13375
13375
 
13376
13376
  ${(()=>{t.registerUniform(`outputSize`,`u32`);for(let n=0;n<e.length;n++)t.registerUniform(`sizeInConcatAxis${n}`,`u32`);return t.declareVariables(...o,d)})()}
13377
13377
 
13378
- ${zq(a.length,p)}
13378
+ ${Vq(a.length,p)}
13379
13379
 
13380
13380
  ${t.mainStart()}
13381
13381
  ${t.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.outputSize`)}
@@ -13388,12 +13388,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
13388
13388
  ${f} -= sizeInConcatAxis[inputIndex - 1u];
13389
13389
  }
13390
13390
 
13391
- ${Bq(o,d)}
13392
- }`}},Hq=(e,t)=>{let n=e.inputs,r=n[0].dims,i=Q.normalizeAxis(t.axis,r.length);Rq(n,i);let a=r.slice();a[i]=n.reduce((e,t)=>e+(t.dims.length>i?t.dims[i]:0),0);let o=n.filter(e=>Q.size(e.dims)>0);e.compute(Vq(o,i,a,n[0].dataType),{inputs:o})},Uq=e=>FW({axis:e.axis})}),Gq,Kq,qq,Jq,Yq=Z(()=>{VU(),iW(),Gq=(e,t,n=`f32`)=>{switch(e.activation){case`Relu`:return`value = max(value, ${t}(0.0));`;case`Sigmoid`:return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case`Clip`:return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case`HardSigmoid`:return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case`LeakyRelu`:return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case`Tanh`:return`let e2x = exp(-2.0 * abs(value));
13391
+ ${Hq(o,d)}
13392
+ }`}},Wq=(e,t)=>{let n=e.inputs,r=n[0].dims,i=Q.normalizeAxis(t.axis,r.length);Bq(n,i);let a=r.slice();a[i]=n.reduce((e,t)=>e+(t.dims.length>i?t.dims[i]:0),0);let o=n.filter(e=>Q.size(e.dims)>0);e.compute(Uq(o,i,a,n[0].dataType),{inputs:o})},Gq=e=>LW({axis:e.axis})}),qq,Jq,Yq,Xq,Zq=Z(()=>{UU(),oW(),qq=(e,t,n=`f32`)=>{switch(e.activation){case`Relu`:return`value = max(value, ${t}(0.0));`;case`Sigmoid`:return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case`Clip`:return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case`HardSigmoid`:return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case`LeakyRelu`:return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case`Tanh`:return`let e2x = exp(-2.0 * abs(value));
13393
13393
  value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
13394
- `;case``:return``;default:throw Error(`Unsupported activation ${e.activation}`)}},Kq=(e,t)=>{e.activation===`Clip`?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===`HardSigmoid`?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===`LeakyRelu`&&t.push({type:1,data:e.alpha})},qq=(e,t)=>{e.activation===`Clip`?t.push({name:`clip_max`,type:`f32`},{name:`clip_min`,type:`f32`}):e.activation===`HardSigmoid`?t.push({name:`alpha`,type:`f32`},{name:`beta`,type:`f32`}):e.activation===`LeakyRelu`&&t.push({name:`alpha`,type:`f32`})},Jq=e=>{let t=e?.activation||``;if(t===`HardSigmoid`){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}else if(t===`Clip`){let[n,r]=e?.activation_params||[nW,rW];return{activation:t,clipMax:r,clipMin:n}}else if(t===`LeakyRelu`){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),Xq,Zq,Qq=Z(()=>{Xq=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw Error(`${e}-component is not supported.`)}},Zq=e=>`
13394
+ `;case``:return``;default:throw Error(`Unsupported activation ${e.activation}`)}},Jq=(e,t)=>{e.activation===`Clip`?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===`HardSigmoid`?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===`LeakyRelu`&&t.push({type:1,data:e.alpha})},Yq=(e,t)=>{e.activation===`Clip`?t.push({name:`clip_max`,type:`f32`},{name:`clip_min`,type:`f32`}):e.activation===`HardSigmoid`?t.push({name:`alpha`,type:`f32`},{name:`beta`,type:`f32`}):e.activation===`LeakyRelu`&&t.push({name:`alpha`,type:`f32`})},Xq=e=>{let t=e?.activation||``;if(t===`HardSigmoid`){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}else if(t===`Clip`){let[n,r]=e?.activation_params||[iW,aW];return{activation:t,clipMax:r,clipMin:n}}else if(t===`LeakyRelu`){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),Qq,$q,eJ=Z(()=>{Qq=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw Error(`${e}-component is not supported.`)}},$q=e=>`
13395
13395
  ${e?`value = value + getBiasByOutputCoords(coords);`:``}
13396
- `}),$q,eJ=Z(()=>{$q=e=>`
13396
+ `}),tJ,nJ=Z(()=>{tJ=e=>`
13397
13397
  fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
13398
13398
  return dot(coords, vec4<i32>(
13399
13399
  shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
@@ -13402,14 +13402,14 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
13402
13402
  return dot(coords, vec4<i32>(
13403
13403
  i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
13404
13404
  }
13405
- `}),tJ,nJ,rJ=Z(()=>{VU(),iW(),$W(),Yq(),tJ=(e,t,n,r,i)=>{let a=r-n;return`
13405
+ `}),rJ,iJ,aJ=Z(()=>{UU(),oW(),tG(),Zq(),rJ=(e,t,n,r,i)=>{let a=r-n;return`
13406
13406
  ${Array.from({length:n}).map((n,o)=>`
13407
- if (${KW(t.shape,o,t.rank)} != 1) {
13408
- ${t.indicesSet(e,o,KW(i,o+a,r))}
13407
+ if (${JW(t.shape,o,t.rank)} != 1) {
13408
+ ${t.indicesSet(e,o,JW(i,o+a,r))}
13409
13409
  } else {
13410
13410
  ${t.indicesSet(e,o,0)}
13411
13411
  }`).join(``)}
13412
- `},nJ=(e,t,n,r,i=!1,a)=>{let o=e[0].dims,s=e[1].dims,c=o[o.length-2],l=s[s.length-1],u=o[o.length-1],d=HW(l),f=HW(u),p=HW(c),m=Q.size(n)/d/p,h=e.length>2,g=r?r.slice(0,-2):n.slice(0,-2),_=[Q.size(g),c,l],v=[{type:12,data:m},{type:12,data:c},{type:12,data:l},{type:12,data:u}];return Kq(t,v),v.push(...VW(g,o,s)),h&&v.push(...VW(e[2].dims)),v.push(...VW(_)),{name:`MatMulNaive`,shaderCache:{hint:`${t.activation};${d};${f};${p};${i}`,inputDependencies:h?[`rank`,`rank`,`rank`]:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:v}),getShaderSource:r=>{let a=XW(`batch_dims`,e[0].dataType,g.length),c=$(`a`,e[0].dataType,o.length,f),l=$(`b`,e[1].dataType,s.length,d),u=JW(`output`,e[0].dataType,_.length,d),m=zW(u.type.tensor),v=Gq(t,u.type.value,m),y=[c,l],b=``;if(h){let t=i?d:1;y.push($(`bias`,e[2].dataType,e[2].dims.length,t)),b=`${i?`value += bias[col / ${t}];`:`value += ${u.type.value}(bias[row + i]);`}`}let x=[{name:`output_size`,type:`u32`},{name:`M`,type:`u32`},{name:`N`,type:`u32`},{name:`K`,type:`u32`}];qq(t,x);let S=()=>{let e=`var a_data: ${c.type.value};`;for(let t=0;t<f;t++)e+=`
13412
+ `},iJ=(e,t,n,r,i=!1,a)=>{let o=e[0].dims,s=e[1].dims,c=o[o.length-2],l=s[s.length-1],u=o[o.length-1],d=WW(l),f=WW(u),p=WW(c),m=Q.size(n)/d/p,h=e.length>2,g=r?r.slice(0,-2):n.slice(0,-2),_=[Q.size(g),c,l],v=[{type:12,data:m},{type:12,data:c},{type:12,data:l},{type:12,data:u}];return Jq(t,v),v.push(...UW(g,o,s)),h&&v.push(...UW(e[2].dims)),v.push(...UW(_)),{name:`MatMulNaive`,shaderCache:{hint:`${t.activation};${d};${f};${p};${i}`,inputDependencies:h?[`rank`,`rank`,`rank`]:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:v}),getShaderSource:r=>{let a=QW(`batch_dims`,e[0].dataType,g.length),c=$(`a`,e[0].dataType,o.length,f),l=$(`b`,e[1].dataType,s.length,d),u=XW(`output`,e[0].dataType,_.length,d),m=VW(u.type.tensor),v=qq(t,u.type.value,m),y=[c,l],b=``;if(h){let t=i?d:1;y.push($(`bias`,e[2].dataType,e[2].dims.length,t)),b=`${i?`value += bias[col / ${t}];`:`value += ${u.type.value}(bias[row + i]);`}`}let x=[{name:`output_size`,type:`u32`},{name:`M`,type:`u32`},{name:`N`,type:`u32`},{name:`K`,type:`u32`}];Yq(t,x);let S=()=>{let e=`var a_data: ${c.type.value};`;for(let t=0;t<f;t++)e+=`
13413
13413
  let b_data${t} = b[(b_offset + (k + ${t}) * uniforms.N + col) / ${d}];`;for(let t=0;t<p;t++){e+=`a_data = a[(a_offset + (row + ${t}) * uniforms.K + k) / ${f}];`;for(let n=0;n<f;n++)e+=`
13414
13414
  values[${t}] = fma(${l.type.value}(a_data${f===1?``:`[${n}]`}), b_data${n}, values[${t}]);
13415
13415
  `}return e};return`
@@ -13425,13 +13425,13 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
13425
13425
  ${n.length===2?``:`let batch_indices = ${a.offsetToIndices(`batch`)};`}
13426
13426
 
13427
13427
  var a_indices: ${c.type.indices};
13428
- ${tJ(`a_indices`,c,c.rank-2,a.rank,`batch_indices`)}
13428
+ ${rJ(`a_indices`,c,c.rank-2,a.rank,`batch_indices`)}
13429
13429
  ${c.indicesSet(`a_indices`,c.rank-2,0)}
13430
13430
  ${c.indicesSet(`a_indices`,c.rank-1,0)}
13431
13431
  let a_offset = ${c.indicesToOffset(`a_indices`)};
13432
13432
 
13433
13433
  var b_indices: ${l.type.indices};
13434
- ${tJ(`b_indices`,l,l.rank-2,a.rank,`batch_indices`)}
13434
+ ${rJ(`b_indices`,l,l.rank-2,a.rank,`batch_indices`)}
13435
13435
  ${l.indicesSet(`b_indices`,l.rank-2,0)}
13436
13436
  ${l.indicesSet(`b_indices`,l.rank-1,0)}
13437
13437
  let b_offset = ${l.indicesToOffset(`b_indices`)};
@@ -13448,7 +13448,7 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
13448
13448
  ${u.setByOffset(`offset / ${d}`,`value`)};
13449
13449
  }
13450
13450
  }
13451
- `}}}}),iJ,aJ,oJ,sJ,cJ,lJ,uJ,dJ,fJ=Z(()=>{VU(),iW(),$W(),Yq(),rJ(),Qq(),iJ=(e,t)=>e?`
13451
+ `}}}}),oJ,sJ,cJ,lJ,uJ,dJ,fJ,pJ,mJ=Z(()=>{UU(),oW(),tG(),Zq(),aJ(),eJ(),oJ=(e,t)=>e?`
13452
13452
  mm_Asub[inputRow][inputCol] = mm_readA(batch,
13453
13453
  kStart + inputRow,
13454
13454
  globalRowStart / innerElementSize + inputCol${t?`, batchIndices`:``});
@@ -13456,7 +13456,7 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
13456
13456
  mm_Asub[inputRow][inputCol] = mm_readA(batch,
13457
13457
  globalRow + innerRow,
13458
13458
  kStart / innerElementSize + inputCol${t?`, batchIndices`:``});
13459
- `,aJ=(e,t)=>e?`
13459
+ `,sJ=(e,t)=>e?`
13460
13460
  let ACached0 = mm_Asub[k * innerElementSize][localRow];
13461
13461
  let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
13462
13462
  let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
@@ -13473,7 +13473,7 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
13473
13473
  acc[i] = BCached1 * ACached.y + acc[i];
13474
13474
  acc[i] = BCached2 * ACached.z + acc[i];
13475
13475
  ${t===3?``:`acc[i] = BCached3 * ACached.w + acc[i];`}
13476
- }`,oJ=(e,t,n=`f32`,r,i=!1,a=32,o=!1,s=32)=>{let c=t[1]*e[1],l=t[0]*e[0],u=i?c:a,d=i?a:c,f=u/t[0],p=a/t[1];if(!((i&&f===4&&e[1]===4||!i&&(f===3||f===4))&&u%t[0]===0&&a%t[1]===0&&e[0]===4))throw Error(`If transposeA ${i} is true, innerElementSize ${f} and workPerThread[1] ${e[1]} must be 4.
13476
+ }`,cJ=(e,t,n=`f32`,r,i=!1,a=32,o=!1,s=32)=>{let c=t[1]*e[1],l=t[0]*e[0],u=i?c:a,d=i?a:c,f=u/t[0],p=a/t[1];if(!((i&&f===4&&e[1]===4||!i&&(f===3||f===4))&&u%t[0]===0&&a%t[1]===0&&e[0]===4))throw Error(`If transposeA ${i} is true, innerElementSize ${f} and workPerThread[1] ${e[1]} must be 4.
13477
13477
  Otherwise, innerElementSize ${f} must be 3 or 4.
13478
13478
  tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`
13479
13479
  var<workgroup> mm_Asub: array<array<vec${f}<${n}>, ${u/f}>, ${d}>;
@@ -13510,7 +13510,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13510
13510
  for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
13511
13511
  let inputRow = tileRow + innerRow;
13512
13512
  let inputCol = tileCol;
13513
- ${iJ(i,r)}
13513
+ ${oJ(i,r)}
13514
13514
  }
13515
13515
 
13516
13516
  // Load one tile of B into local memory.
@@ -13529,7 +13529,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13529
13529
  let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];
13530
13530
  ${f===3?``:`let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];`}
13531
13531
 
13532
- ${aJ(i,f)}
13532
+ ${sJ(i,f)}
13533
13533
  }
13534
13534
 
13535
13535
  workgroupBarrier();
@@ -13538,7 +13538,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13538
13538
  for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
13539
13539
  mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
13540
13540
  }
13541
- }`},sJ=(e,t)=>e?`
13541
+ }`},lJ=(e,t)=>e?`
13542
13542
  mm_Asub[inputRow][inputCol] = mm_readA(batch,
13543
13543
  kStart + inputRow,
13544
13544
  globalRowStart + inputCol${t?`, batchIndices`:``});
@@ -13546,7 +13546,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13546
13546
  mm_Asub[inputRow][inputCol] = mm_readA(batch,
13547
13547
  globalRowStart + inputRow,
13548
13548
  kStart + inputCol${t?`, batchIndices`:``});
13549
- `,cJ=e=>e?`let ACached = mm_Asub[k][tileRow + innerRow];`:`let ACached = mm_Asub[tileRow + innerRow][k];`,lJ=(e,t,n=`f32`,r,i=!1,a=32,o=!1,s=32,c=!1)=>{let l=e[1]*t[1],u=e[0]*t[0],d=i?l:a,f=i?a:l;if(!(f%t[1]===0&&d%t[0]===0&&a%t[1]===0))throw Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let p=f/t[1],m=d/t[0],h=a/t[1],g=c?`
13549
+ `,uJ=e=>e?`let ACached = mm_Asub[k][tileRow + innerRow];`:`let ACached = mm_Asub[tileRow + innerRow][k];`,dJ=(e,t,n=`f32`,r,i=!1,a=32,o=!1,s=32,c=!1)=>{let l=e[1]*t[1],u=e[0]*t[0],d=i?l:a,f=i?a:l;if(!(f%t[1]===0&&d%t[0]===0&&a%t[1]===0))throw Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let p=f/t[1],m=d/t[0],h=a/t[1],g=c?`
13550
13550
  let localRow = i32(localId.y);
13551
13551
  let localCol = i32(localId.x);
13552
13552
  let globalRowStart = i32(workgroupId.y) * ${l};
@@ -13557,7 +13557,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13557
13557
  // Load one tile of A into local memory.
13558
13558
  for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${t[1]}) {
13559
13559
  for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {
13560
- ${sJ(i,r)}
13560
+ ${lJ(i,r)}
13561
13561
  }
13562
13562
  }
13563
13563
  // Load one tile of B into local memory.
@@ -13612,7 +13612,7 @@ for (var t = 0; t < num_tiles; t = t + 1) {
13612
13612
  for (var innerCol = 0; innerCol < ${m}; innerCol = innerCol + 1) {
13613
13613
  let inputRow = tileRowA + innerRow;
13614
13614
  let inputCol = tileColA + innerCol;
13615
- ${sJ(i,r)}
13615
+ ${lJ(i,r)}
13616
13616
  }
13617
13617
  }
13618
13618
 
@@ -13637,7 +13637,7 @@ for (var t = 0; t < num_tiles; t = t + 1) {
13637
13637
  }
13638
13638
 
13639
13639
  for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
13640
- ${cJ(i)}
13640
+ ${uJ(i)}
13641
13641
  for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
13642
13642
  acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
13643
13643
  }
@@ -13672,14 +13672,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13672
13672
  var acc : array<array<${n}, colPerThread>, rowPerThread>;
13673
13673
  ${g}
13674
13674
  }
13675
- `},uJ=(e,t,n,r,i=!1)=>{let[a,o,s,c]=r,l=zW(r[0].type.tensor);return`
13676
- fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Xq(e,l)} {
13677
- var value = ${Xq(e,l)}(0.0);
13675
+ `},fJ=(e,t,n,r,i=!1)=>{let[a,o,s,c]=r,l=VW(r[0].type.tensor);return`
13676
+ fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Qq(e,l)} {
13677
+ var value = ${Qq(e,l)}(0.0);
13678
13678
  let col = colIn * ${e};
13679
13679
  if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
13680
13680
  {
13681
13681
  var aIndices: ${o.type.indices};
13682
- ${tJ(`aIndices`,o,o.rank-2,a.rank,`batchIndices`)}
13682
+ ${rJ(`aIndices`,o,o.rank-2,a.rank,`batchIndices`)}
13683
13683
  ${o.indicesSet(`aIndices`,o.rank-2,`u32(row)`)}
13684
13684
  ${o.indicesSet(`aIndices`,o.rank-1,`u32(colIn)`)}
13685
13685
  value = ${o.getByIndices(`aIndices`)};
@@ -13687,13 +13687,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13687
13687
  return value;
13688
13688
  }
13689
13689
 
13690
- fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Xq(e,l)} {
13691
- var value = ${Xq(e,l)}(0.0);
13690
+ fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Qq(e,l)} {
13691
+ var value = ${Qq(e,l)}(0.0);
13692
13692
  let col = colIn * ${e};
13693
13693
  if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
13694
13694
  {
13695
13695
  var bIndices: ${s.type.indices};
13696
- ${tJ(`bIndices`,s,s.rank-2,a.rank,`batchIndices`)}
13696
+ ${rJ(`bIndices`,s,s.rank-2,a.rank,`batchIndices`)}
13697
13697
  ${s.indicesSet(`bIndices`,s.rank-2,`u32(row)`)}
13698
13698
  ${s.indicesSet(`bIndices`,s.rank-1,`u32(colIn)`)}
13699
13699
  value = ${s.getByIndices(`bIndices`)};
@@ -13701,21 +13701,21 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13701
13701
  return value;
13702
13702
  }
13703
13703
 
13704
- fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Xq(e,l)}) {
13704
+ fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Qq(e,l)}) {
13705
13705
  let col = colIn * ${e};
13706
13706
  if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
13707
13707
  var value = valueIn;
13708
13708
  let coords = vec3<i32>(batch, row, colIn);
13709
- ${t?`value = value + ${i?`bias[colIn]`:`${Xq(e,l)}(bias[row])`};`:``}
13709
+ ${t?`value = value + ${i?`bias[colIn]`:`${Qq(e,l)}(bias[row])`};`:``}
13710
13710
  ${n}
13711
13711
  ${c.setByIndices(`vec3<u32>(coords)`,`value`)}
13712
13712
  }
13713
13713
  }
13714
- `},dJ=(e,t,n,r,i=!1,a)=>{let o=e[0].dims,s=e[1].dims,c=o.slice(0,-2),l=s.slice(0,-2),u=r?r.slice(0,-2):n.slice(0,-2),d=Q.size(u),f=o[o.length-2],p=o[o.length-1],m=s[s.length-1],h=p%4==0&&m%4==0,g=f<=8?[4,1,1]:[4,4,1],_=[8,8,1],v=[Math.ceil(m/_[0]/g[0]),Math.ceil(f/_[1]/g[1]),Math.ceil(d/_[2]/g[2])],y=h?4:1,b=[...c,f,p/y],x=b.length,S=[...l,p,m/y],C=S.length,w=[d,f,m/y],T=[{type:6,data:f},{type:6,data:m},{type:6,data:p}];Kq(t,T),T.push(...VW(u,b,S));let E=[`rank`,`rank`],D=e.length>2;return D&&(T.push(...VW(e[2].dims)),E.push(`rank`)),T.push(...VW(w)),{name:`MatMul`,shaderCache:{hint:`${g};${t.activation};${h};${i}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:T}),getShaderSource:n=>{let r=u.length,a=XW(`batchDims`,e[0].dataType,r,1),o=zW(e[0].dataType),s=$(`a`,e[0].dataType,x,y),c=$(`b`,e[1].dataType,C,y),l=JW(`result`,e[0].dataType,w.length,y),d=[s,c];if(D){let t=i?y:1;d.push($(`bias`,e[2].dataType,e[2].dims.length,t))}let f=[{name:`dim_a_outer`,type:`i32`},{name:`dim_b_outer`,type:`i32`},{name:`dim_inner`,type:`i32`}];qq(t,f);let p=zW(l.type.tensor),m=Gq(t,l.type.value,p),v=uJ(y,D,m,[a,s,c,l],i);return`
13714
+ `},pJ=(e,t,n,r,i=!1,a)=>{let o=e[0].dims,s=e[1].dims,c=o.slice(0,-2),l=s.slice(0,-2),u=r?r.slice(0,-2):n.slice(0,-2),d=Q.size(u),f=o[o.length-2],p=o[o.length-1],m=s[s.length-1],h=p%4==0&&m%4==0,g=f<=8?[4,1,1]:[4,4,1],_=[8,8,1],v=[Math.ceil(m/_[0]/g[0]),Math.ceil(f/_[1]/g[1]),Math.ceil(d/_[2]/g[2])],y=h?4:1,b=[...c,f,p/y],x=b.length,S=[...l,p,m/y],C=S.length,w=[d,f,m/y],T=[{type:6,data:f},{type:6,data:m},{type:6,data:p}];Jq(t,T),T.push(...UW(u,b,S));let E=[`rank`,`rank`],D=e.length>2;return D&&(T.push(...UW(e[2].dims)),E.push(`rank`)),T.push(...UW(w)),{name:`MatMul`,shaderCache:{hint:`${g};${t.activation};${h};${i}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:T}),getShaderSource:n=>{let r=u.length,a=QW(`batchDims`,e[0].dataType,r,1),o=VW(e[0].dataType),s=$(`a`,e[0].dataType,x,y),c=$(`b`,e[1].dataType,C,y),l=XW(`result`,e[0].dataType,w.length,y),d=[s,c];if(D){let t=i?y:1;d.push($(`bias`,e[2].dataType,e[2].dims.length,t))}let f=[{name:`dim_a_outer`,type:`i32`},{name:`dim_b_outer`,type:`i32`},{name:`dim_inner`,type:`i32`}];Yq(t,f);let p=VW(l.type.tensor),m=qq(t,l.type.value,p),v=fJ(y,D,m,[a,s,c,l],i);return`
13715
13715
  ${n.registerUniforms(f).registerInternalVariables(a).declareVariables(...d,l)}
13716
13716
  ${v}
13717
- ${h?oJ(g,_,o,a):lJ(g,_,o,a)}
13718
- `}}}}),pJ,mJ,hJ=Z(()=>{VU(),ZU(),$W(),Yq(),Qq(),eJ(),fJ(),pJ=(e,t,n,r,i=!1,a,o=4,s=4,c=4,l=`f32`)=>{let u=e=>{switch(e){case 1:return`resData = x[xIndex];`;case 3:return`resData = vec3<${l}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return`resData = x[xIndex / 4];`;default:throw Error(`innerElementSize ${e} is not supported.`)}},d=e=>{switch(e){case 1:return`return w[row * i32(uniforms.w_shape[3]) + colIn];`;case 4:return`return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];`;default:throw Error(`innerElementSize ${e} is not supported.`)}},f=e?`
13717
+ ${h?cJ(g,_,o,a):dJ(g,_,o,a)}
13718
+ `}}}}),hJ,gJ,_J=Z(()=>{UU(),$U(),tG(),Zq(),eJ(),nJ(),mJ(),hJ=(e,t,n,r,i=!1,a,o=4,s=4,c=4,l=`f32`)=>{let u=e=>{switch(e){case 1:return`resData = x[xIndex];`;case 3:return`resData = vec3<${l}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return`resData = x[xIndex / 4];`;default:throw Error(`innerElementSize ${e} is not supported.`)}},d=e=>{switch(e){case 1:return`return w[row * i32(uniforms.w_shape[3]) + colIn];`;case 4:return`return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];`;default:throw Error(`innerElementSize ${e} is not supported.`)}},f=e?`
13719
13719
  let coord = vec4<i32>(batch, xRow, xCol, xCh);
13720
13720
  `:`
13721
13721
  let coord = vec4<i32>(batch, xCh, xRow, xCol);
@@ -13742,7 +13742,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13742
13742
  let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
13743
13743
  let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
13744
13744
  let xCh = ${_} % inChannels;
13745
- var resData = ${Xq(o,l)}(0.0);
13745
+ var resData = ${Qq(o,l)}(0.0);
13746
13746
  // The bounds checking is always needed since we use it to pad zero for
13747
13747
  // the 'same' padding type.
13748
13748
  if (xRow >= 0 && xRow < ${m} && xCol >= 0 && xCol < ${h}) {
@@ -13757,24 +13757,24 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13757
13757
  if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
13758
13758
  ${v}
13759
13759
  }
13760
- return ${Xq(o,l)}(0.0);`:r&&n?`
13760
+ return ${Qq(o,l)}(0.0);`:r&&n?`
13761
13761
  let col = colIn * ${o};
13762
13762
  ${v}`:`
13763
13763
  let col = colIn * ${o};
13764
13764
  if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
13765
13765
  ${v}
13766
13766
  }
13767
- return ${Xq(o,l)}(0.0);`,b=e?r&&n?d(s):`
13767
+ return ${Qq(o,l)}(0.0);`,b=e?r&&n?d(s):`
13768
13768
  let col = colIn * ${s};
13769
13769
  if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
13770
13770
  ${d(s)}
13771
13771
  }
13772
- return ${Xq(s,l)}(0.0);`:`
13772
+ return ${Qq(s,l)}(0.0);`:`
13773
13773
  let col = colIn * ${s};
13774
13774
  if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
13775
13775
  ${d(s)}
13776
13776
  }
13777
- return ${Xq(s,l)}(0.0);`,x=Xq(c,l),S=Xq(e?o:s,l),C=Xq(e?s:o,l),w=Gq(a,x,l);return`
13777
+ return ${Qq(s,l)}(0.0);`,x=Qq(c,l),S=Qq(e?o:s,l),C=Qq(e?s:o,l),w=qq(a,x,l);return`
13778
13778
  fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${S} {
13779
13779
  ${e?y:b}
13780
13780
  }
@@ -13790,32 +13790,32 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13790
13790
  var value = valueIn;
13791
13791
  let outWidth = ${e?`i32(uniforms.result_shape[2])`:`i32(uniforms.result_shape[3])`};
13792
13792
  ${p}
13793
- ${Zq(i)}
13793
+ ${$q(i)}
13794
13794
  ${w}
13795
13795
  setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
13796
13796
  }
13797
- }`},mJ=(e,t,n,r,i,a,o,s,c)=>{let l=t.format===`NHWC`,u=l?e[0].dims[3]:e[0].dims[1],d=n[0],f=l?n[2]:n[3],p=l?n[1]:n[2],m=l?n[3]:n[1],h=l&&(u%4==0||u%3==0)&&m%4==0,g=l?m:f*p,_=l?f*p:m,v=[8,8,1],y=r<=8?[4,1,1]:[4,4,1],b=[Math.ceil(g/v[0]/y[0]),Math.ceil(_/v[1]/y[1]),Math.ceil(d/v[2]/y[2])];XU(`verbose`,()=>`[conv2d_mm_webgpu] dispatch = ${b}`);let x=h?l&&u%4!=0?3:4:1,S=v[1]*y[1],C=v[0]*y[0],w=Math.max(v[0]*x,v[1]),T=r%S===0,E=i%C===0,D=a%w===0,O=h?[x,4,4]:[1,1,1],k=[{type:6,data:r},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Kq(t,k),k.push(...VW(e[0].dims,e[1].dims));let A=[`rank`,`rank`];return o&&(k.push(...VW(e[2].dims)),A.push(`rank`)),k.push(...VW(n)),{name:`Conv2DMatMul`,shaderCache:{hint:`${t.cacheKey};${x};${h};${T};${E};${D};${S};${C};${w}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:c?c(n):n,dataType:e[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:k}),getShaderSource:r=>{let i=[{name:`dim_a_outer`,type:`i32`},{name:`dim_b_outer`,type:`i32`},{name:`dim_inner`,type:`i32`},{name:`pad`,type:`i32`,length:2},{name:`stride`,type:`i32`,length:2},{name:`dilation`,type:`i32`,length:2}];qq(t,i);let a=h?4:1,c=zW(e[0].dataType),u=`
13797
+ }`},gJ=(e,t,n,r,i,a,o,s,c)=>{let l=t.format===`NHWC`,u=l?e[0].dims[3]:e[0].dims[1],d=n[0],f=l?n[2]:n[3],p=l?n[1]:n[2],m=l?n[3]:n[1],h=l&&(u%4==0||u%3==0)&&m%4==0,g=l?m:f*p,_=l?f*p:m,v=[8,8,1],y=r<=8?[4,1,1]:[4,4,1],b=[Math.ceil(g/v[0]/y[0]),Math.ceil(_/v[1]/y[1]),Math.ceil(d/v[2]/y[2])];QU(`verbose`,()=>`[conv2d_mm_webgpu] dispatch = ${b}`);let x=h?l&&u%4!=0?3:4:1,S=v[1]*y[1],C=v[0]*y[0],w=Math.max(v[0]*x,v[1]),T=r%S===0,E=i%C===0,D=a%w===0,O=h?[x,4,4]:[1,1,1],k=[{type:6,data:r},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Jq(t,k),k.push(...UW(e[0].dims,e[1].dims));let A=[`rank`,`rank`];return o&&(k.push(...UW(e[2].dims)),A.push(`rank`)),k.push(...UW(n)),{name:`Conv2DMatMul`,shaderCache:{hint:`${t.cacheKey};${x};${h};${T};${E};${D};${S};${C};${w}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:c?c(n):n,dataType:e[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:k}),getShaderSource:r=>{let i=[{name:`dim_a_outer`,type:`i32`},{name:`dim_b_outer`,type:`i32`},{name:`dim_inner`,type:`i32`},{name:`pad`,type:`i32`,length:2},{name:`stride`,type:`i32`,length:2},{name:`dilation`,type:`i32`,length:2}];Yq(t,i);let a=h?4:1,c=VW(e[0].dataType),u=`
13798
13798
  fn setOutputAtIndex(flatIndex : i32, value : ${h?`vec4<${c}>`:c}) {
13799
13799
  result[flatIndex] = ${h?`vec4<${c}>`:c}(value);
13800
13800
  }
13801
13801
  fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${h?`vec4<${c}>`:c}) {
13802
13802
  let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
13803
13803
  setOutputAtIndex(flatIndex ${h?`/ 4`:``}, value);
13804
- }`,d=[$(`x`,e[0].dataType,e[0].dims.length,x===3?1:x),$(`w`,e[1].dataType,e[1].dims.length,a)],f=JW(`result`,e[0].dataType,n.length,a);if(o){let t=$(`bias`,e[2].dataType,e[2].dims.length,a);d.push(t),u+=`
13804
+ }`,d=[$(`x`,e[0].dataType,e[0].dims.length,x===3?1:x),$(`w`,e[1].dataType,e[1].dims.length,a)],f=XW(`result`,e[0].dataType,n.length,a);if(o){let t=$(`bias`,e[2].dataType,e[2].dims.length,a);d.push(t),u+=`
13805
13805
  fn getBiasByOutputCoords(coords : vec4<i32>) -> ${h?`vec4<${c}>`:c} {
13806
13806
  return bias[coords.${l?`w`:`y`}${h?`/ 4`:``}];
13807
13807
  }`}return`
13808
- ${$q(`uniforms.result_strides`)}
13808
+ ${tJ(`uniforms.result_strides`)}
13809
13809
  //struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,
13810
13810
  // outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,
13811
13811
  // dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
13812
13812
  ${r.registerUniforms(i).declareVariables(...d,f)}
13813
13813
  ${u}
13814
- ${pJ(l,T,E,D,o,t,O[0],O[1],O[2],c)}
13815
- ${h?oJ(y,v,c,void 0,!l,w):lJ(y,v,c,void 0,!l,w,!1,void 0,s)}`}}}}),gJ,_J,vJ,yJ,bJ,xJ,SJ,CJ,wJ=Z(()=>{VU(),ZU(),iW(),$W(),Yq(),Qq(),gJ=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t},_J=e=>typeof e==`number`?[e,e,e]:e,vJ=(e,t)=>t<=1?e:e+(e-1)*(t-1),yJ=(e,t,n,r=1)=>{let i=vJ(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)},bJ=(e,t,n,r,i)=>{i??=yJ(e,t[0],r[0]);let a=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*i>=t[n]&&(a[n]=Math.trunc((e[n]-t[n]+2*i)/r[n]+1));return a},xJ=(e,t,n,r,i,a,o,s,c,l)=>{let u,d,f,p;if(e===`VALID`&&(e=0),typeof e==`number`){u={top:e,bottom:e,left:e,right:e,front:e,back:e};let m=bJ([t,n,r,1],[s,c,l],1,[i,a,o],e);d=m[0],f=m[1],p=m[2]}else if(Array.isArray(e)){if(!e.every((e,t,n)=>e===n[0]))throw Error(`Unsupported padding parameter: ${e}`);u={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let m=bJ([t,n,r,1],[s,c,l],1,[i,a,o],e[0]);d=m[0],f=m[1],p=m[2]}else if(e===`SAME_UPPER`){d=Math.ceil(t/i),f=Math.ceil(n/a),p=Math.ceil(r/o);let e=(d-1)*i+s-t,m=(f-1)*a+c-n,h=(p-1)*o+l-r,g=Math.floor(e/2),_=e-g,v=Math.floor(m/2),y=m-v,b=Math.floor(h/2);u={top:v,bottom:y,left:b,right:h-b,front:g,back:_}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outDepth:d,outHeight:f,outWidth:p}},SJ=(e,t,n,r,i,a=!1,o=`channelsLast`)=>{let s,c,l,u,d;if(o===`channelsLast`)[s,c,l,u,d]=e;else if(o===`channelsFirst`)[s,d,c,l,u]=e;else throw Error(`Unknown dataFormat ${o}`);let[f,,p,m,h]=t,[g,_,v]=_J(n),[y,b,x]=_J(r),S=vJ(p,y),C=vJ(m,b),w=vJ(h,x),{padInfo:T,outDepth:E,outHeight:D,outWidth:O}=xJ(i,c,l,u,g,_,v,S,C,w),k=a?f*d:f,A=[0,0,0,0,0];return o===`channelsFirst`?A=[s,k,E,D,O]:o===`channelsLast`&&(A=[s,E,D,O,k]),{batchSize:s,dataFormat:o,inDepth:c,inHeight:l,inWidth:u,inChannels:d,outDepth:E,outHeight:D,outWidth:O,outChannels:k,padInfo:T,strideDepth:g,strideHeight:_,strideWidth:v,filterDepth:p,filterHeight:m,filterWidth:h,effectiveFilterDepth:S,effectiveFilterHeight:C,effectiveFilterWidth:w,dilationDepth:y,dilationHeight:b,dilationWidth:x,inShape:e,outShape:A,filterShape:t}},CJ=(e,t,n,r,i,a)=>{let o=a===`channelsLast`;o?e[0].dims[3]:e[0].dims[1];let s=[64,1,1],c={x:n.map((e,t)=>t)},l=[Math.ceil(gJ(c.x.map(e=>n[e]))/s[0]),1,1];XU(`verbose`,()=>`[conv3d_naive_webgpu] dispatch = ${l}`);let u=[{type:12,data:Q.size(n)},{type:12,data:r},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Kq(t,u),u.push(...VW(e[0].dims,e[1].dims));let d=[`rank`,`rank`],f=e.length===3;return f&&(u.push(...VW(e[2].dims)),d.push(`rank`)),u.push(...VW(n)),{name:`Conv3DNaive`,shaderCache:{hint:`${t.cacheKey};${o};1;${f}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:l[0],y:l[1],z:l[2]},programUniforms:u}),getShaderSource:a=>{let s=[{name:`output_size`,type:`u32`},{name:`filter_dims`,type:`u32`,length:r.length},{name:`pads`,type:`u32`,length:i.length},{name:`strides`,type:`u32`,length:t.strides.length},{name:`dilations`,type:`u32`,length:t.dilations.length}];qq(t,s);let c=zW(e[0].dataType),l=$(`x`,e[0].dataType,e[0].dims.length,1),u=$(`W`,e[1].dataType,e[1].dims.length,1),d=[l,u],p=JW(`result`,e[0].dataType,n.length,1),m=``;if(f){let t=$(`bias`,e[2].dataType,e[2].dims.length,1);d.push(t),m+=`
13814
+ ${hJ(l,T,E,D,o,t,O[0],O[1],O[2],c)}
13815
+ ${h?cJ(y,v,c,void 0,!l,w):dJ(y,v,c,void 0,!l,w,!1,void 0,s)}`}}}}),vJ,yJ,bJ,xJ,SJ,CJ,wJ,TJ,EJ=Z(()=>{UU(),$U(),oW(),tG(),Zq(),eJ(),vJ=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t},yJ=e=>typeof e==`number`?[e,e,e]:e,bJ=(e,t)=>t<=1?e:e+(e-1)*(t-1),xJ=(e,t,n,r=1)=>{let i=bJ(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)},SJ=(e,t,n,r,i)=>{i??=xJ(e,t[0],r[0]);let a=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*i>=t[n]&&(a[n]=Math.trunc((e[n]-t[n]+2*i)/r[n]+1));return a},CJ=(e,t,n,r,i,a,o,s,c,l)=>{let u,d,f,p;if(e===`VALID`&&(e=0),typeof e==`number`){u={top:e,bottom:e,left:e,right:e,front:e,back:e};let m=SJ([t,n,r,1],[s,c,l],1,[i,a,o],e);d=m[0],f=m[1],p=m[2]}else if(Array.isArray(e)){if(!e.every((e,t,n)=>e===n[0]))throw Error(`Unsupported padding parameter: ${e}`);u={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let m=SJ([t,n,r,1],[s,c,l],1,[i,a,o],e[0]);d=m[0],f=m[1],p=m[2]}else if(e===`SAME_UPPER`){d=Math.ceil(t/i),f=Math.ceil(n/a),p=Math.ceil(r/o);let e=(d-1)*i+s-t,m=(f-1)*a+c-n,h=(p-1)*o+l-r,g=Math.floor(e/2),_=e-g,v=Math.floor(m/2),y=m-v,b=Math.floor(h/2);u={top:v,bottom:y,left:b,right:h-b,front:g,back:_}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outDepth:d,outHeight:f,outWidth:p}},wJ=(e,t,n,r,i,a=!1,o=`channelsLast`)=>{let s,c,l,u,d;if(o===`channelsLast`)[s,c,l,u,d]=e;else if(o===`channelsFirst`)[s,d,c,l,u]=e;else throw Error(`Unknown dataFormat ${o}`);let[f,,p,m,h]=t,[g,_,v]=yJ(n),[y,b,x]=yJ(r),S=bJ(p,y),C=bJ(m,b),w=bJ(h,x),{padInfo:T,outDepth:E,outHeight:D,outWidth:O}=CJ(i,c,l,u,g,_,v,S,C,w),k=a?f*d:f,A=[0,0,0,0,0];return o===`channelsFirst`?A=[s,k,E,D,O]:o===`channelsLast`&&(A=[s,E,D,O,k]),{batchSize:s,dataFormat:o,inDepth:c,inHeight:l,inWidth:u,inChannels:d,outDepth:E,outHeight:D,outWidth:O,outChannels:k,padInfo:T,strideDepth:g,strideHeight:_,strideWidth:v,filterDepth:p,filterHeight:m,filterWidth:h,effectiveFilterDepth:S,effectiveFilterHeight:C,effectiveFilterWidth:w,dilationDepth:y,dilationHeight:b,dilationWidth:x,inShape:e,outShape:A,filterShape:t}},TJ=(e,t,n,r,i,a)=>{let o=a===`channelsLast`;o?e[0].dims[3]:e[0].dims[1];let s=[64,1,1],c={x:n.map((e,t)=>t)},l=[Math.ceil(vJ(c.x.map(e=>n[e]))/s[0]),1,1];QU(`verbose`,()=>`[conv3d_naive_webgpu] dispatch = ${l}`);let u=[{type:12,data:Q.size(n)},{type:12,data:r},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Jq(t,u),u.push(...UW(e[0].dims,e[1].dims));let d=[`rank`,`rank`],f=e.length===3;return f&&(u.push(...UW(e[2].dims)),d.push(`rank`)),u.push(...UW(n)),{name:`Conv3DNaive`,shaderCache:{hint:`${t.cacheKey};${o};1;${f}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:l[0],y:l[1],z:l[2]},programUniforms:u}),getShaderSource:a=>{let s=[{name:`output_size`,type:`u32`},{name:`filter_dims`,type:`u32`,length:r.length},{name:`pads`,type:`u32`,length:i.length},{name:`strides`,type:`u32`,length:t.strides.length},{name:`dilations`,type:`u32`,length:t.dilations.length}];Yq(t,s);let c=VW(e[0].dataType),l=$(`x`,e[0].dataType,e[0].dims.length,1),u=$(`W`,e[1].dataType,e[1].dims.length,1),d=[l,u],p=XW(`result`,e[0].dataType,n.length,1),m=``;if(f){let t=$(`bias`,e[2].dataType,e[2].dims.length,1);d.push(t),m+=`
13816
13816
  fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${c} {
13817
- return bias[${o?KW(`coords`,4,5):KW(`coords`,1,5)}];
13818
- }`}let h=Xq(1,c),g=Gq(t,h,c);return`
13817
+ return bias[${o?JW(`coords`,4,5):JW(`coords`,1,5)}];
13818
+ }`}let h=Qq(1,c),g=qq(t,h,c);return`
13819
13819
  ${m}
13820
13820
  fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
13821
13821
  let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
@@ -13829,18 +13829,18 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13829
13829
  ${a.mainStart()}
13830
13830
  ${a.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
13831
13831
  let coords = ${p.offsetToIndices(`global_idx`)};
13832
- let batch = ${KW(`coords`,0,l.rank)};
13833
- let d2 = ${o?KW(`coords`,l.rank-1,l.rank):KW(`coords`,1,l.rank)};
13834
- let xFRCCorner = vec3<u32>(${o?KW(`coords`,1,l.rank):KW(`coords`,2,l.rank)},
13835
- ${o?KW(`coords`,2,l.rank):KW(`coords`,3,l.rank)},
13836
- ${o?KW(`coords`,3,l.rank):KW(`coords`,4,l.rank)}) * uniforms.strides - uniforms.pads;
13832
+ let batch = ${JW(`coords`,0,l.rank)};
13833
+ let d2 = ${o?JW(`coords`,l.rank-1,l.rank):JW(`coords`,1,l.rank)};
13834
+ let xFRCCorner = vec3<u32>(${o?JW(`coords`,1,l.rank):JW(`coords`,2,l.rank)},
13835
+ ${o?JW(`coords`,2,l.rank):JW(`coords`,3,l.rank)},
13836
+ ${o?JW(`coords`,3,l.rank):JW(`coords`,4,l.rank)}) * uniforms.strides - uniforms.pads;
13837
13837
  let xFCorner = xFRCCorner.x;
13838
13838
  let xRCorner = xFRCCorner.y;
13839
13839
  let xCCorner = xFRCCorner.z;
13840
- let xShapeY = ${o?KW(`uniforms.x_shape`,1,l.rank):KW(`uniforms.x_shape`,2,l.rank)};
13841
- let xShapeZ = ${o?KW(`uniforms.x_shape`,2,l.rank):KW(`uniforms.x_shape`,3,l.rank)};
13842
- let xShapeW = ${o?KW(`uniforms.x_shape`,3,l.rank):KW(`uniforms.x_shape`,4,l.rank)};
13843
- let xShapeU = ${o?KW(`uniforms.x_shape`,4,l.rank):KW(`uniforms.x_shape`,1,l.rank)};
13840
+ let xShapeY = ${o?JW(`uniforms.x_shape`,1,l.rank):JW(`uniforms.x_shape`,2,l.rank)};
13841
+ let xShapeZ = ${o?JW(`uniforms.x_shape`,2,l.rank):JW(`uniforms.x_shape`,3,l.rank)};
13842
+ let xShapeW = ${o?JW(`uniforms.x_shape`,3,l.rank):JW(`uniforms.x_shape`,4,l.rank)};
13843
+ let xShapeU = ${o?JW(`uniforms.x_shape`,4,l.rank):JW(`uniforms.x_shape`,1,l.rank)};
13844
13844
  let inputDepthNearestVec4 = (xShapeU / 4) * 4;
13845
13845
  let inputDepthVec4Remainder = xShapeU % 4;
13846
13846
 
@@ -13920,7 +13920,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13920
13920
  ${f?`value = value + getBiasByOutputCoords(coords)`:``};
13921
13921
  ${g}
13922
13922
  result[global_idx] = f32(value);
13923
- }`}}}}),TJ,EJ,DJ=Z(()=>{VU(),iW(),$W(),Yq(),TJ=(e,t,n,r)=>{let i=e.length>2,a=i?`value += b[output_channel];`:``,o=e[0].dims,s=e[1].dims,c=t.format===`NHWC`,l=c?n[3]:n[1],u=l/t.group,d=c&&u>=4?HW(l):1,f=Q.size(n)/d,p=[{type:12,data:f},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:u}];Kq(t,p),p.push(...VW(o,[s[0],s[1],s[2],s[3]/d]));let m=i?[`rank`,`rank`,`rank`]:[`rank`,`rank`];return p.push(...VW([n[0],n[1],n[2],n[3]/d])),{name:`GroupedConv`,shaderCache:{hint:`${t.cacheKey}_${d}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:p}),getShaderSource:r=>{let l=JW(`output`,e[0].dataType,n.length,d),u=zW(l.type.tensor),f=Gq(t,l.type.value,u),p=$(`x`,e[0].dataType,o.length),m=$(`w`,e[1].dataType,s.length,d),h=[p,m];i&&h.push($(`b`,e[2].dataType,e[2].dims,d));let g=[{name:`output_size`,type:`u32`},{name:`dilations`,type:`u32`,length:t.dilations.length},{name:`strides`,type:`u32`,length:2},{name:`pads`,type:`u32`,length:2},{name:`output_channels_per_group`,type:`u32`}];qq(t,g);let _=c?`
13923
+ }`}}}}),DJ,OJ,kJ=Z(()=>{UU(),oW(),tG(),Zq(),DJ=(e,t,n,r)=>{let i=e.length>2,a=i?`value += b[output_channel];`:``,o=e[0].dims,s=e[1].dims,c=t.format===`NHWC`,l=c?n[3]:n[1],u=l/t.group,d=c&&u>=4?WW(l):1,f=Q.size(n)/d,p=[{type:12,data:f},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:u}];Jq(t,p),p.push(...UW(o,[s[0],s[1],s[2],s[3]/d]));let m=i?[`rank`,`rank`,`rank`]:[`rank`,`rank`];return p.push(...UW([n[0],n[1],n[2],n[3]/d])),{name:`GroupedConv`,shaderCache:{hint:`${t.cacheKey}_${d}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:p}),getShaderSource:r=>{let l=XW(`output`,e[0].dataType,n.length,d),u=VW(l.type.tensor),f=qq(t,l.type.value,u),p=$(`x`,e[0].dataType,o.length),m=$(`w`,e[1].dataType,s.length,d),h=[p,m];i&&h.push($(`b`,e[2].dataType,e[2].dims,d));let g=[{name:`output_size`,type:`u32`},{name:`dilations`,type:`u32`,length:t.dilations.length},{name:`strides`,type:`u32`,length:2},{name:`pads`,type:`u32`,length:2},{name:`output_channels_per_group`,type:`u32`}];Yq(t,g);let _=c?`
13924
13924
  for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
13925
13925
  let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
13926
13926
 
@@ -13982,7 +13982,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
13982
13982
  ${a}
13983
13983
  ${f}
13984
13984
  ${l.setByOffset(`global_idx`,`value`)}
13985
- }`}}},EJ=(e,t,n,r)=>{let i=e.length>2,a=HW(n[3]),o=HW(n[2]),s=Q.size(n)/a/o,c=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],l=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],u=[n[0],n[1],n[2],n[3]/a],d=[{type:12,data:s},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Kq(t,d),d.push(...VW(c,l,u));let f=(o-1)*t.strides[1]+l[1];return{name:`GroupedConv-Vectorize`,shaderCache:{hint:`${t.cacheKey};${a};${o};${f};${l[0]};${l[1]}`,inputDependencies:i?[`rank`,`rank`,`type`]:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d}),getShaderSource:n=>{let r=JW(`output`,e[0].dataType,u.length,a),s=zW(r.type.tensor),d=Gq(t,r.type.value,s),p=$(`x`,e[0].dataType,c.length,a),m=$(`w`,e[1].dataType,l.length,a),h=[p,m];i&&h.push($(`b`,e[2].dataType,e[2].dims,a));let g=i?`value += b[output_channel];`:``,_=[{name:`output_size`,type:`u32`},{name:`strides`,type:`i32`,length:2},{name:`pads`,type:`i32`,length:2}];return qq(t,_),`
13985
+ }`}}},OJ=(e,t,n,r)=>{let i=e.length>2,a=WW(n[3]),o=WW(n[2]),s=Q.size(n)/a/o,c=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],l=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],u=[n[0],n[1],n[2],n[3]/a],d=[{type:12,data:s},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Jq(t,d),d.push(...UW(c,l,u));let f=(o-1)*t.strides[1]+l[1];return{name:`GroupedConv-Vectorize`,shaderCache:{hint:`${t.cacheKey};${a};${o};${f};${l[0]};${l[1]}`,inputDependencies:i?[`rank`,`rank`,`type`]:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d}),getShaderSource:n=>{let r=XW(`output`,e[0].dataType,u.length,a),s=VW(r.type.tensor),d=qq(t,r.type.value,s),p=$(`x`,e[0].dataType,c.length,a),m=$(`w`,e[1].dataType,l.length,a),h=[p,m];i&&h.push($(`b`,e[2].dataType,e[2].dims,a));let g=i?`value += b[output_channel];`:``,_=[{name:`output_size`,type:`u32`},{name:`strides`,type:`i32`,length:2},{name:`pads`,type:`i32`,length:2}];return Yq(t,_),`
13986
13986
  ${n.registerUniforms(_).declareVariables(...h,r)}
13987
13987
  ${n.mainStart()}
13988
13988
  ${n.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -14027,7 +14027,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14027
14027
  ${d}
14028
14028
  ${r.set(`batch`,`row`,`col + i`,`output_channel`,`value`)};
14029
14029
  }
14030
- }`}}}}),OJ,kJ,AJ,jJ,MJ,NJ,PJ,FJ,IJ,LJ=Z(()=>{iW(),hJ(),wJ(),fJ(),DJ(),Yq(),rJ(),lG(),OJ=(e,t,n,r,i,a)=>{let o=e[0],s=e.slice(a?1:2,a?3:4),c=s.length,l=t[0],u=t.slice(2).map((e,t)=>e+(e-1)*(n[t]-1)),d=s.map((e,t)=>e+r[t]+r[t+c]).map((e,t)=>Math.floor((e-u[t]+i[t])/i[t]));return d.splice(0,0,o),d.splice(a?3:1,0,l),d},kJ=[2,3,1,0],AJ=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw Error(`Conv requires 2 or 3 inputs`);if(e[0].dims.length>5)throw Error(`greater than 5D is not supported`);if(e[0].dims.length!==e[1].dims.length)throw Error(`filter does not have same dimension as input`);if(e[0].dims[t.format===`NHWC`?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw Error(`FILTER_IN_CHANNEL should be equal to DATA_CHANNEL`);if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw Error(`invalid bias`);let n=e[0].dims.length-2;if(t.dilations.length!==n)throw Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw Error(`invalid kernel shape`)},jJ=(e,t)=>{let n=e.kernelShape.slice();n.length<t[1].dims.length-2&&n.push(...Array(t[1].dims.length-2-n.length).fill(0));for(let e=2;e<t[1].dims.length;++e)n[e-2]===0&&(n[e-2]=t[1].dims[e]);let r=e.pads.slice();eW.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,r,e.format===`NHWC`,e.autoPad);let i=Object.assign({},e);return Object.assign(i,{kernelShape:n,pads:r}),i},MJ=e=>{let t=Jq(e),n=e.format;return{autoPad:[`NOTSET`,`VALID`,`SAME_UPPER`,`SAME_LOWER`][e.auto_pad],format:n,dilations:e.dilations,group:e.group,kernelShape:e.kernel_shape,pads:e.pads,strides:e.strides,wIsConst:e.w_is_const(),...t,cacheKey:`${e.format};${t.activation};`}},NJ=(e,t,n,r)=>{let i=n.format===`NHWC`,a=OJ(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,i);if(n.group!==1){let o=[t[0]];if(i){let r=e.kernelCustomData.wT??e.compute(oG(t[1],kJ),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),o.push(r)}else o.push(t[1]);t.length===3&&o.push(t[2]),!e.adapterInfo.isArchitecture(`ampere`)&&i&&t[1].dims[0]===n.group&&t[1].dims[1]===1&&n.dilations[0]===1&&n.dilations[1]===1?e.compute(EJ(o,n,a,r),{inputs:o}):e.compute(TJ(o,n,a,r),{inputs:o});return}let o=t.length===3,s=t[0].dims[i?1:2],c=t[0].dims[i?2:3],l=t[0].dims[i?3:1],u=t[1].dims[2],d=t[1].dims[3],f=a[i?1:2],p=a[i?2:3],m=a[i?3:1],h=i&&u===s&&d===c&&n.pads[0]===0&&n.pads[1]===0;if(h||u===1&&d===1&&n.dilations[0]===1&&n.dilations[1]===1&&n.strides[0]===1&&n.strides[1]===1&&n.pads[0]===0&&n.pads[1]===0){let u=a[0],d,g,_,v=[];if(i){let r=e.kernelCustomData.wT??e.compute(oG(t[1],kJ),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),h){let e=s*c*l;d=t[0].reshape([1,u,e]),g=r.reshape([1,e,m]),_=[1,u,m]}else d=t[0].reshape([u,s*c,l]),g=r.reshape([1,l,m]),_=[u,f*p,m];v.push(d),v.push(g)}else d=t[0].reshape([u,l,s*c]),g=t[1].reshape([1,m,l]),_=[u,m,f*p],v.push(g),v.push(d);o&&v.push(t[2]);let y=_[2],b=v[0].dims[v[0].dims.length-1];y<8&&b<8?e.compute(nJ(v,n,a,_,i,r),{inputs:v}):e.compute(dJ(v,n,a,_,i,r),{inputs:v});return}let g=e.kernelCustomData.wT??e.compute(oG(t[1],kJ),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let _=[t[0],g];o&&_.push(t[2]);let v=i?f*p:m,y=i?m:f*p,b=u*d*l;e.compute(mJ(_,n,a,v,y,b,o,!0,r),{inputs:_})},PJ=(e,t)=>{let n=t.format===`NHWC`,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&r.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),o=[1].concat(t.dilations),s=[1].concat(t.kernelShape),c=jJ({...t,pads:i,strides:a,dilations:o,kernelShape:s},r);NJ(e,r,c,e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])},FJ=(e,t,n)=>{let r=n.format===`NHWC`?`channelsLast`:`channelsFirst`,i=jJ(n,t),a=n.autoPad===`NOTSET`?n.pads:n.autoPad,o=SJ(t[0].dims,t[1].dims,n.strides,n.dilations,a,!1,r);e.compute(CJ(t,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],r))},IJ=(e,t)=>{if(AJ(e.inputs,t),e.inputs[0].dims.length===3)PJ(e,t);else if(e.inputs[0].dims.length===5)FJ(e,e.inputs,t);else{let n=jJ(t,e.inputs);NJ(e,e.inputs,n)}}}),RJ,zJ=Z(()=>{VU(),ZU(),iW(),$W(),RJ=(e,t,n)=>{let r=e.length>2,i=t.outputShape,a=t.format===`NHWC`,o=t.group,s=e[1].dims,c=s[2]/o,l=s[3],u=a?HW(c):1,d=a&&l===1&&c>=4,f=d?Math.floor(c/4)*4:Math.floor(c/u)*u,p=c-f,m=a?HW(l):1,h=a?l===1?u:m:1,g=Q.size(i)/m,_=[Math.ceil(g/64),1,1];XU(`verbose`,()=>`[conv2d_backprop_webgpu] dispatch = ${_}`);let v=[`rank`,`rank`],y=[t.strides[0],t.strides[1]],b=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],x=[t.dilations[0],t.dilations[1]],S=[b[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),b[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],C=[S[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),S[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],w=[{type:12,data:g},{type:12,data:y},{type:12,data:b},{type:12,data:x},{type:12,data:S},{type:6,data:C},{type:12,data:f},{type:12,data:c},{type:12,data:l},...VW(e[0].dims,e[1].dims)];return r&&(w.push(...VW(e[2].dims)),v.push(`rank`)),w.push(...VW(i)),{name:`ConvTranspose2D`,shaderCache:{hint:`${t.cacheKey};${u}${h}${m}${d}${p}`,inputDependencies:v},getRunData:()=>({dispatchGroup:{x:_[0],y:_[1],z:_[2]},outputs:[{dims:n?n(i):i,dataType:e[0].dataType}],programUniforms:w}),getShaderSource:t=>{let n=[{name:`output_size`,type:`u32`},{name:`strides`,type:`u32`,length:y.length},{name:`filter_dims`,type:`u32`,length:b.length},{name:`dilations`,type:`u32`,length:b.length},{name:`effective_filter_dims`,type:`u32`,length:S.length},{name:`pads`,type:`i32`,length:C.length},{name:`input_channels_per_group_int`,type:`u32`},{name:`input_channels_per_group`,type:`u32`},{name:`output_channels_per_group`,type:`u32`}],o=zW(e[0].dataType),s=a?1:2,c=a?2:3,l=a?3:1,f=$(`W`,e[1].dataType,e[1].dims.length,h),g=$(`Dy`,e[0].dataType,e[0].dims.length,u),_=[g,f];r&&_.push($(`bias`,e[2].dataType,[i[l]].length,m));let v=JW(`result`,e[0].dataType,i.length,m),x=`
14030
+ }`}}}}),AJ,jJ,MJ,NJ,PJ,FJ,IJ,LJ,RJ,zJ=Z(()=>{oW(),_J(),EJ(),mJ(),kJ(),Zq(),aJ(),dG(),AJ=(e,t,n,r,i,a)=>{let o=e[0],s=e.slice(a?1:2,a?3:4),c=s.length,l=t[0],u=t.slice(2).map((e,t)=>e+(e-1)*(n[t]-1)),d=s.map((e,t)=>e+r[t]+r[t+c]).map((e,t)=>Math.floor((e-u[t]+i[t])/i[t]));return d.splice(0,0,o),d.splice(a?3:1,0,l),d},jJ=[2,3,1,0],MJ=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw Error(`Conv requires 2 or 3 inputs`);if(e[0].dims.length>5)throw Error(`greater than 5D is not supported`);if(e[0].dims.length!==e[1].dims.length)throw Error(`filter does not have same dimension as input`);if(e[0].dims[t.format===`NHWC`?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw Error(`FILTER_IN_CHANNEL should be equal to DATA_CHANNEL`);if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw Error(`invalid bias`);let n=e[0].dims.length-2;if(t.dilations.length!==n)throw Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw Error(`invalid kernel shape`)},NJ=(e,t)=>{let n=e.kernelShape.slice();n.length<t[1].dims.length-2&&n.push(...Array(t[1].dims.length-2-n.length).fill(0));for(let e=2;e<t[1].dims.length;++e)n[e-2]===0&&(n[e-2]=t[1].dims[e]);let r=e.pads.slice();nW.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,r,e.format===`NHWC`,e.autoPad);let i=Object.assign({},e);return Object.assign(i,{kernelShape:n,pads:r}),i},PJ=e=>{let t=Xq(e),n=e.format;return{autoPad:[`NOTSET`,`VALID`,`SAME_UPPER`,`SAME_LOWER`][e.auto_pad],format:n,dilations:e.dilations,group:e.group,kernelShape:e.kernel_shape,pads:e.pads,strides:e.strides,wIsConst:e.w_is_const(),...t,cacheKey:`${e.format};${t.activation};`}},FJ=(e,t,n,r)=>{let i=n.format===`NHWC`,a=AJ(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,i);if(n.group!==1){let o=[t[0]];if(i){let r=e.kernelCustomData.wT??e.compute(cG(t[1],jJ),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),o.push(r)}else o.push(t[1]);t.length===3&&o.push(t[2]),!e.adapterInfo.isArchitecture(`ampere`)&&i&&t[1].dims[0]===n.group&&t[1].dims[1]===1&&n.dilations[0]===1&&n.dilations[1]===1?e.compute(OJ(o,n,a,r),{inputs:o}):e.compute(DJ(o,n,a,r),{inputs:o});return}let o=t.length===3,s=t[0].dims[i?1:2],c=t[0].dims[i?2:3],l=t[0].dims[i?3:1],u=t[1].dims[2],d=t[1].dims[3],f=a[i?1:2],p=a[i?2:3],m=a[i?3:1],h=i&&u===s&&d===c&&n.pads[0]===0&&n.pads[1]===0;if(h||u===1&&d===1&&n.dilations[0]===1&&n.dilations[1]===1&&n.strides[0]===1&&n.strides[1]===1&&n.pads[0]===0&&n.pads[1]===0){let u=a[0],d,g,_,v=[];if(i){let r=e.kernelCustomData.wT??e.compute(cG(t[1],jJ),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),h){let e=s*c*l;d=t[0].reshape([1,u,e]),g=r.reshape([1,e,m]),_=[1,u,m]}else d=t[0].reshape([u,s*c,l]),g=r.reshape([1,l,m]),_=[u,f*p,m];v.push(d),v.push(g)}else d=t[0].reshape([u,l,s*c]),g=t[1].reshape([1,m,l]),_=[u,m,f*p],v.push(g),v.push(d);o&&v.push(t[2]);let y=_[2],b=v[0].dims[v[0].dims.length-1];y<8&&b<8?e.compute(iJ(v,n,a,_,i,r),{inputs:v}):e.compute(pJ(v,n,a,_,i,r),{inputs:v});return}let g=e.kernelCustomData.wT??e.compute(cG(t[1],jJ),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let _=[t[0],g];o&&_.push(t[2]);let v=i?f*p:m,y=i?m:f*p,b=u*d*l;e.compute(gJ(_,n,a,v,y,b,o,!0,r),{inputs:_})},IJ=(e,t)=>{let n=t.format===`NHWC`,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&r.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),o=[1].concat(t.dilations),s=[1].concat(t.kernelShape),c=NJ({...t,pads:i,strides:a,dilations:o,kernelShape:s},r);FJ(e,r,c,e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])},LJ=(e,t,n)=>{let r=n.format===`NHWC`?`channelsLast`:`channelsFirst`,i=NJ(n,t),a=n.autoPad===`NOTSET`?n.pads:n.autoPad,o=wJ(t[0].dims,t[1].dims,n.strides,n.dilations,a,!1,r);e.compute(TJ(t,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],r))},RJ=(e,t)=>{if(MJ(e.inputs,t),e.inputs[0].dims.length===3)IJ(e,t);else if(e.inputs[0].dims.length===5)LJ(e,e.inputs,t);else{let n=NJ(t,e.inputs);FJ(e,e.inputs,n)}}}),BJ,VJ=Z(()=>{UU(),$U(),oW(),tG(),BJ=(e,t,n)=>{let r=e.length>2,i=t.outputShape,a=t.format===`NHWC`,o=t.group,s=e[1].dims,c=s[2]/o,l=s[3],u=a?WW(c):1,d=a&&l===1&&c>=4,f=d?Math.floor(c/4)*4:Math.floor(c/u)*u,p=c-f,m=a?WW(l):1,h=a?l===1?u:m:1,g=Q.size(i)/m,_=[Math.ceil(g/64),1,1];QU(`verbose`,()=>`[conv2d_backprop_webgpu] dispatch = ${_}`);let v=[`rank`,`rank`],y=[t.strides[0],t.strides[1]],b=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],x=[t.dilations[0],t.dilations[1]],S=[b[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),b[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],C=[S[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),S[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],w=[{type:12,data:g},{type:12,data:y},{type:12,data:b},{type:12,data:x},{type:12,data:S},{type:6,data:C},{type:12,data:f},{type:12,data:c},{type:12,data:l},...UW(e[0].dims,e[1].dims)];return r&&(w.push(...UW(e[2].dims)),v.push(`rank`)),w.push(...UW(i)),{name:`ConvTranspose2D`,shaderCache:{hint:`${t.cacheKey};${u}${h}${m}${d}${p}`,inputDependencies:v},getRunData:()=>({dispatchGroup:{x:_[0],y:_[1],z:_[2]},outputs:[{dims:n?n(i):i,dataType:e[0].dataType}],programUniforms:w}),getShaderSource:t=>{let n=[{name:`output_size`,type:`u32`},{name:`strides`,type:`u32`,length:y.length},{name:`filter_dims`,type:`u32`,length:b.length},{name:`dilations`,type:`u32`,length:b.length},{name:`effective_filter_dims`,type:`u32`,length:S.length},{name:`pads`,type:`i32`,length:C.length},{name:`input_channels_per_group_int`,type:`u32`},{name:`input_channels_per_group`,type:`u32`},{name:`output_channels_per_group`,type:`u32`}],o=VW(e[0].dataType),s=a?1:2,c=a?2:3,l=a?3:1,f=$(`W`,e[1].dataType,e[1].dims.length,h),g=$(`Dy`,e[0].dataType,e[0].dims.length,u),_=[g,f];r&&_.push($(`bias`,e[2].dataType,[i[l]].length,m));let v=XW(`result`,e[0].dataType,i.length,m),x=`
14031
14031
  let outputIndices = ${v.offsetToIndices(`global_idx * ${m}`)};
14032
14032
  let batch = ${v.indicesGet(`outputIndices`,0)};
14033
14033
  let d1 = ${v.indicesGet(`outputIndices`,l)};
@@ -14115,7 +14115,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14115
14115
  ${t.registerUniforms(n).declareVariables(..._,v)}
14116
14116
  ${t.mainStart()}
14117
14117
  ${t.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)};
14118
- ${x}}`}}}}),BJ,VJ,HJ,UJ,WJ,GJ,KJ,qJ,JJ,YJ=Z(()=>{zJ(),Yq(),lG(),BJ=(e,t,n,r,i,a)=>(e-1)*t+n+(r-1)*i+1-a,VJ=(e,t,n,r,i)=>{let a=Math.floor(e/2);t===`SAME_UPPER`?(n[r]=a,n[i]=e-a):t===`SAME_LOWER`&&(n[r]=e-a,n[i]=a)},HJ=(e,t,n,r,i,a,o,s,c,l)=>{let u=e.length-2,d=l.length===0;c.length<u&&c.push(...Array(u-c.length).fill(0));let f=e[0],p=t[s?3:1]*i;for(let i=0,f=e.length-u-+!!s;i<u;++i,++f){let s=e[f],p=d?s*o[i]:l[i],m=BJ(s,o[i],a[i],t[f],n[i],p);VJ(m,r,a,i,i+u),d&&l.push(o[i]*(s-1)+c[i]+(t[f]-1)*n[i]+1-a[i]-a[i+u])}l.splice(0,0,f),l.splice(s?3:1,0,p)},UJ=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((e,t)=>e*t,1)===0){n.length=0;for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e])}let r=e.format===`NHWC`;n.splice(0,0,t[1].dims[0]),n.splice(r?3:1,0,t[1].dims[1]);let i=e.pads.slice(),a=e.outputShape.slice(),o=e.outputPadding.slice(),s=t[0].dims,c=e.dilations.slice();if(c.reduce((e,t)=>e+t,0)===0){let e=t[0].dims.length-2;c=Array(e).fill(1)}let l=e.strides.slice();if(l.reduce((e,t)=>e+t,0)===0){let e=t[0].dims.length-2;l=Array(e).fill(1)}HJ(s,n,c,e.autoPad,e.group,i,l,r,o,a);let u=Object.assign({},e);return Object.assign(u,{kernelShape:n,pads:i,outputPadding:o,outputShape:a,dilations:c,strides:l}),u},WJ=e=>{let t=Jq(e),n=e.format,r=[`NOTSET`,`VALID`,`SAME_UPPER`,`SAME_LOWER`][typeof e.autoPad>`u`?0:e.autoPad],i=e.dilations,a=e.group??1,o=e.kernelShape,s=e.pads,c=e.strides,l=e.wIsConst();return{autoPad:r,format:n,dilations:i,group:a,kernelShape:o,outputPadding:e.outputPadding,outputShape:e.outputShape,pads:s,strides:c,wIsConst:l,...t,cacheKey:`${e.format};${t.activation};`}},GJ=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw Error(`Conv requires 2 or 3 inputs`);if(e[0].dims.length!==4&&e[0].dims.length!==3)throw Error(`currently only support 2-dimensional conv`);if(e[0].dims.length!==e[1].dims.length)throw Error(`filter does not have same dimension as input`);if(e[0].dims[t.format===`NHWC`?e[0].dims.length-1:1]!==e[1].dims[0])throw Error(`FILTER_IN_CHANNEL should be equal to DATA_CHANNEL`);let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw Error(`invalid bias`);let r=e[0].dims.length-2;if(t.dilations.reduce((e,t)=>e+t,0)>0&&t.dilations.length!==r)throw Error(`dilations should be ${r}D`);if(t.strides.reduce((e,t)=>e+t,0)>0&&t.strides.length!==r)throw Error(`strides should be ${r}D`);if(t.pads.reduce((e,t)=>e+t,0)>0&&t.pads.length!==r*2)throw Error(`pads should be ${r*2}D`);if(t.outputPadding.length!==r&&t.outputPadding.length!==0)throw Error(`output_padding should be ${r}D`);if(t.kernelShape.reduce((e,t)=>e+t,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw Error(`invalid kernel shape`);if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw Error(`invalid output shape`)},KJ=(e,t,n,r)=>{let i=e.kernelCustomData.wT??e.compute(oG(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let a=[t[0],i];t.length===3&&a.push(t[2]),e.compute(RJ(a,n,r),{inputs:a})},qJ=(e,t)=>{let n=t.format===`NHWC`,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&r.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let s=t.pads;s.length===0&&(s=[0,0]),s=[0,s[0],0,s[1]],o=[1].concat(o),a=[1].concat(a),i=[1].concat(i);let c=t.outputPadding;c=[0].concat(c);let l=UJ({...t,pads:s,strides:o,dilations:a,kernelShape:i,outputPadding:c},r);KJ(e,r,l,e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])},JJ=(e,t)=>{if(GJ(e.inputs,t),e.inputs[0].dims.length===3)qJ(e,t);else{let n=UJ(t,e.inputs);KJ(e,e.inputs,n)}}}),XJ,ZJ,QJ,$J=Z(()=>{VU(),iW(),IW(),$W(),XJ=(e,t,n,r)=>{let i=Q.size(t),a=t.length,o=$(`input`,e,a),s=JW(`output`,e,a),c=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),l=Q.normalizeAxis(c,a);return{name:`CumSum`,shaderCache:{hint:r.cacheKey,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:l},...VW(t,t)]}),getShaderSource:e=>{let t=` i32(${o.indicesGet(`inputIndices`,`uniforms.axis`)}) `,n=KW(`uniforms.input_shape`,`uniforms.axis`,a),i=r.reverse?t+(r.exclusive?` + 1`:``):`0`,c=r.reverse?n:t+(r.exclusive?``:` + 1`);return`
14118
+ ${x}}`}}}}),HJ,UJ,WJ,GJ,KJ,qJ,JJ,YJ,XJ,ZJ=Z(()=>{VJ(),Zq(),dG(),HJ=(e,t,n,r,i,a)=>(e-1)*t+n+(r-1)*i+1-a,UJ=(e,t,n,r,i)=>{let a=Math.floor(e/2);t===`SAME_UPPER`?(n[r]=a,n[i]=e-a):t===`SAME_LOWER`&&(n[r]=e-a,n[i]=a)},WJ=(e,t,n,r,i,a,o,s,c,l)=>{let u=e.length-2,d=l.length===0;c.length<u&&c.push(...Array(u-c.length).fill(0));let f=e[0],p=t[s?3:1]*i;for(let i=0,f=e.length-u-+!!s;i<u;++i,++f){let s=e[f],p=d?s*o[i]:l[i],m=HJ(s,o[i],a[i],t[f],n[i],p);UJ(m,r,a,i,i+u),d&&l.push(o[i]*(s-1)+c[i]+(t[f]-1)*n[i]+1-a[i]-a[i+u])}l.splice(0,0,f),l.splice(s?3:1,0,p)},GJ=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((e,t)=>e*t,1)===0){n.length=0;for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e])}let r=e.format===`NHWC`;n.splice(0,0,t[1].dims[0]),n.splice(r?3:1,0,t[1].dims[1]);let i=e.pads.slice(),a=e.outputShape.slice(),o=e.outputPadding.slice(),s=t[0].dims,c=e.dilations.slice();if(c.reduce((e,t)=>e+t,0)===0){let e=t[0].dims.length-2;c=Array(e).fill(1)}let l=e.strides.slice();if(l.reduce((e,t)=>e+t,0)===0){let e=t[0].dims.length-2;l=Array(e).fill(1)}WJ(s,n,c,e.autoPad,e.group,i,l,r,o,a);let u=Object.assign({},e);return Object.assign(u,{kernelShape:n,pads:i,outputPadding:o,outputShape:a,dilations:c,strides:l}),u},KJ=e=>{let t=Xq(e),n=e.format,r=[`NOTSET`,`VALID`,`SAME_UPPER`,`SAME_LOWER`][typeof e.autoPad>`u`?0:e.autoPad],i=e.dilations,a=e.group??1,o=e.kernelShape,s=e.pads,c=e.strides,l=e.wIsConst();return{autoPad:r,format:n,dilations:i,group:a,kernelShape:o,outputPadding:e.outputPadding,outputShape:e.outputShape,pads:s,strides:c,wIsConst:l,...t,cacheKey:`${e.format};${t.activation};`}},qJ=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw Error(`Conv requires 2 or 3 inputs`);if(e[0].dims.length!==4&&e[0].dims.length!==3)throw Error(`currently only support 2-dimensional conv`);if(e[0].dims.length!==e[1].dims.length)throw Error(`filter does not have same dimension as input`);if(e[0].dims[t.format===`NHWC`?e[0].dims.length-1:1]!==e[1].dims[0])throw Error(`FILTER_IN_CHANNEL should be equal to DATA_CHANNEL`);let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw Error(`invalid bias`);let r=e[0].dims.length-2;if(t.dilations.reduce((e,t)=>e+t,0)>0&&t.dilations.length!==r)throw Error(`dilations should be ${r}D`);if(t.strides.reduce((e,t)=>e+t,0)>0&&t.strides.length!==r)throw Error(`strides should be ${r}D`);if(t.pads.reduce((e,t)=>e+t,0)>0&&t.pads.length!==r*2)throw Error(`pads should be ${r*2}D`);if(t.outputPadding.length!==r&&t.outputPadding.length!==0)throw Error(`output_padding should be ${r}D`);if(t.kernelShape.reduce((e,t)=>e+t,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw Error(`invalid kernel shape`);if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw Error(`invalid output shape`)},JJ=(e,t,n,r)=>{let i=e.kernelCustomData.wT??e.compute(cG(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let a=[t[0],i];t.length===3&&a.push(t[2]),e.compute(BJ(a,n,r),{inputs:a})},YJ=(e,t)=>{let n=t.format===`NHWC`,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&r.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let s=t.pads;s.length===0&&(s=[0,0]),s=[0,s[0],0,s[1]],o=[1].concat(o),a=[1].concat(a),i=[1].concat(i);let c=t.outputPadding;c=[0].concat(c);let l=GJ({...t,pads:s,strides:o,dilations:a,kernelShape:i,outputPadding:c},r);JJ(e,r,l,e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])},XJ=(e,t)=>{if(qJ(e.inputs,t),e.inputs[0].dims.length===3)YJ(e,t);else{let n=GJ(t,e.inputs);JJ(e,e.inputs,n)}}}),QJ,$J,eY,tY=Z(()=>{UU(),oW(),RW(),tG(),QJ=(e,t,n,r)=>{let i=Q.size(t),a=t.length,o=$(`input`,e,a),s=XW(`output`,e,a),c=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),l=Q.normalizeAxis(c,a);return{name:`CumSum`,shaderCache:{hint:r.cacheKey,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:l},...UW(t,t)]}),getShaderSource:e=>{let t=` i32(${o.indicesGet(`inputIndices`,`uniforms.axis`)}) `,n=JW(`uniforms.input_shape`,`uniforms.axis`,a),i=r.reverse?t+(r.exclusive?` + 1`:``):`0`,c=r.reverse?n:t+(r.exclusive?``:` + 1`);return`
14119
14119
  ${e.registerUniform(`outputSize`,`u32`).registerUniform(`axis`,`u32`).declareVariables(o,s)}
14120
14120
  ${e.mainStart()}
14121
14121
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.outputSize`)}
@@ -14128,12 +14128,12 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14128
14128
  sum = sum + ${o.getByIndices(`inputIndices`)};
14129
14129
  }
14130
14130
  ${s.setByOffset(`global_idx`,`sum`)};
14131
- }`}}},ZJ=(e,t)=>{let n=e.inputs[0].dims,r=e.inputs[0].dataType,i=e.inputs[1];e.compute(XJ(r,n,i,t),{inputs:[0]})},QJ=e=>{let t=e.exclusive===1,n=e.reverse===1;return FW({exclusive:t,reverse:n})}}),eY,tY,nY,rY,iY,aY=Z(()=>{VU(),iW(),IW(),$W(),eY=e=>{if(!e||e.length!==1)throw Error(`DepthToSpace requires 1 input.`);if(e[0].dims.length!==4)throw Error(`DepthToSpace requires 4D input.`)},tY=(e,t,n,r)=>{let i=[];i.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {
14131
+ }`}}},$J=(e,t)=>{let n=e.inputs[0].dims,r=e.inputs[0].dataType,i=e.inputs[1];e.compute(QJ(r,n,i,t),{inputs:[0]})},eY=e=>{let t=e.exclusive===1,n=e.reverse===1;return LW({exclusive:t,reverse:n})}}),nY,rY,iY,aY,oY,sY=Z(()=>{UU(),oW(),RW(),tG(),nY=e=>{if(!e||e.length!==1)throw Error(`DepthToSpace requires 1 input.`);if(e[0].dims.length!==4)throw Error(`DepthToSpace requires 4D input.`)},rY=(e,t,n,r)=>{let i=[];i.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {
14132
14132
  var a: ${n.type.indices};`);for(let r=0;r<t;++r)i.push(n.indicesSet(`a`,e[r],`i[${r}]`));return i.push(`return a;}`),i.join(`
14133
- `)},nY=(e,t)=>{let n,r,i,a,o,s,c=t.format===`NHWC`,l=t.blocksize,u=t.mode===`DCR`;c?([n,r,i,a]=e.dims,o=u?[n,r,i,l,l,a/l**2]:[n,r,i,a/l**2,l,l],s=u?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,r,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=u?[n,l,l,a/l**2,r,i]:[n,a/l**2,l,l,r,i],s=u?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(o),f=d.dims.length,p=e.dataType,m=$(`a`,p,f),h=JW(`output`,p,f);return{name:`DepthToSpace`,shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:[`rank`]},getRunData:e=>{let t=c?[n,r*l,i*l,a/l**2]:[n,a/l**2,r*l,i*l],o=Q.size(t),u=d.dims,f=Q.sortBasedOnPerm(u,s);return{outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...VW(u,f)]}},getShaderSource:e=>`
14133
+ `)},iY=(e,t)=>{let n,r,i,a,o,s,c=t.format===`NHWC`,l=t.blocksize,u=t.mode===`DCR`;c?([n,r,i,a]=e.dims,o=u?[n,r,i,l,l,a/l**2]:[n,r,i,a/l**2,l,l],s=u?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,r,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=u?[n,l,l,a/l**2,r,i]:[n,a/l**2,l,l,r,i],s=u?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(o),f=d.dims.length,p=e.dataType,m=$(`a`,p,f),h=XW(`output`,p,f);return{name:`DepthToSpace`,shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:[`rank`]},getRunData:e=>{let t=c?[n,r*l,i*l,a/l**2]:[n,a/l**2,r*l,i*l],o=Q.size(t),u=d.dims,f=Q.sortBasedOnPerm(u,s);return{outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...UW(u,f)]}},getShaderSource:e=>`
14134
14134
  ${e.registerUniform(`output_size`,`u32`).declareVariables(m,h)}
14135
14135
 
14136
- ${tY(s,f,m,h)}
14136
+ ${rY(s,f,m,h)}
14137
14137
 
14138
14138
  ${e.mainStart()}
14139
14139
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -14142,8 +14142,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14142
14142
  let aIndices = perm(indices);
14143
14143
 
14144
14144
  ${h.setByOffset(`global_idx`,m.getByIndices(`aIndices`))}
14145
- }`}},rY=(e,t)=>{eY(e.inputs),e.compute(nY(e.inputs[0],t))},iY=e=>FW({blocksize:e.blocksize,mode:e.mode,format:e.format})}),oY,sY,cY,lY,uY,dY,fY,pY,mY,hY,gY,_Y=Z(()=>{VU(),iW(),IW(),$W(),oY=`[a-zA-Z]|\\.\\.\\.`,sY=`(`+oY+`)+`,cY=`^`+sY+`$`,lY=`(`+sY+`,)*`+sY,uY=`^`+lY+`$`,dY=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);n===void 0?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},fY=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=[],this.outputDims=[];let[n,r]=t.includes(`->`)?t.split(`->`,2):[t,``];if(!n.match(RegExp(uY)))throw Error(`Invalid LHS term`);if(n.split(`,`).forEach((t,n)=>{let r=e[n].dims.slice();if(!t.match(RegExp(cY)))throw Error(`Invalid LHS term`);let i=this.processTerm(t,!0,r,n);this.lhs.push(i)}),r===``)r+=[...this.symbolToInfo.entries()].filter(([e,t])=>t.count===1||e===`...`).map(([e])=>e).join(``);else if(!r.match(RegExp(sY)))throw Error(`Invalid RHS`);r.match(RegExp(oY,`g`))?.forEach(e=>{if(e===`...`)this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let t=this.symbolToInfo.get(e);if(t===void 0)throw Error(`Invalid RHS symbol`);this.outputDims.push(t.dimValue)}}),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(e,t,n){let r=this.symbolToInfo.get(e);if(r!==void 0){if(r.dimValue!==t&&r.count!==1)throw Error(`Dimension mismatch`);r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,r)}processTerm(e,t,n,r=-1){let i=n.length,a=!1,o=[],s=0;if(!e.match(RegExp(cY))&&!t&&e!==``)throw Error(`Invalid LHS term`);let c=e.match(RegExp(oY,`g`)),l=new dY(r);return c?.forEach((e,u)=>{if(e===`...`){if(a)throw Error(`Only one ellipsis is allowed per input term`);a=!0;let e=i-c.length+1;if(e<0)throw Error(`Ellipsis out of bounds`);if(o=n.slice(s,s+e),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw Error(`Ellipsis dimensions mismatch`)}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw Error(`Ellipsis must be specified in the LHS`);for(let e=0;e<o.length;e++){let t=String.fromCharCode(48+e);l.addSymbol(t,u+e),this.addSymbol(t,n[s++],r)}}else l.addSymbol(e,u+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(e,n[s++],r)}),l}},pY=e=>e+`_max`,mY=(e,t,n,r)=>{let i=e.map(e=>e.length).map((e,n)=>$(`input${n}`,t,e)),a=Q.size(r),o=JW(`output`,t,r.length),s=[...n.symbolToInfo.keys()].filter(e=>!n.rhs.symbolToIndices.has(e));return{name:`Einsum`,shaderCache:{hint:n.equation,inputDependencies:e.map(()=>`rank`)},getRunData:()=>{let i=s.filter(e=>n.symbolToInfo.has(e)).map(e=>({type:12,data:n.symbolToInfo.get(e)?.dimValue||0}));i.push({type:12,data:a});let o=e.map((e,t)=>[...VW(e)]).reduce((e,t)=>e.concat(t),i);return o.push(...VW(r)),{outputs:[{dims:r,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:o}},getShaderSource:e=>{let t=[],r=[],a=[],c=[],l=[],u=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach((e,s)=>{if(n.rhs.symbolToIndices.has(s)){let r=n.rhs.symbolToIndices.get(s)?.[0];r!==void 0&&n.lhs.forEach((n,a)=>{if(e.inputIndices.includes(a)){let e=n.symbolToIndices.get(s);if(e===void 0)throw Error(`Invalid symbol error`);e.forEach(e=>{t.push(`${i[a].indicesSet(`input${a}Indices`,e,o.indicesGet(`outputIndices`,r))}`)})}})}else n.lhs.forEach((t,n)=>{if(e.inputIndices.includes(n)){let e=t.symbolToIndices.get(s);if(e===void 0)throw Error(`Invalid symbol error`);e.forEach(e=>{r.push(`${i[n].indicesSet(`input${n}Indices`,e,`${s}`)}`)}),l.push(`prod *= ${i[n].getByIndices(`input${n}Indices`)};`)}}),a.push(`for(var ${s}: u32 = 0; ${s} < uniforms.${pY(s)}; ${s}++) {`),c.push(`}`)});let d=u?[...t,`let sum = ${i.map((e,t)=>e.getByIndices(`input${t}Indices`)).join(` * `)};`]:[...t,`var sum = 0.0;`,...a,...r,`var prod = 1.0;`,...l,`sum += prod;`,...c];return`
14146
- ${e.registerUniforms(s.map(e=>({name:`${pY(e)}`,type:`u32`}))).registerUniform(`outputSize`,`u32`).declareVariables(...i,o)}
14145
+ }`}},aY=(e,t)=>{nY(e.inputs),e.compute(iY(e.inputs[0],t))},oY=e=>LW({blocksize:e.blocksize,mode:e.mode,format:e.format})}),cY,lY,uY,dY,fY,pY,mY,hY,gY,_Y,vY,yY=Z(()=>{UU(),oW(),RW(),tG(),cY=`[a-zA-Z]|\\.\\.\\.`,lY=`(`+cY+`)+`,uY=`^`+lY+`$`,dY=`(`+lY+`,)*`+lY,fY=`^`+dY+`$`,pY=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);n===void 0?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},mY=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=[],this.outputDims=[];let[n,r]=t.includes(`->`)?t.split(`->`,2):[t,``];if(!n.match(RegExp(fY)))throw Error(`Invalid LHS term`);if(n.split(`,`).forEach((t,n)=>{let r=e[n].dims.slice();if(!t.match(RegExp(uY)))throw Error(`Invalid LHS term`);let i=this.processTerm(t,!0,r,n);this.lhs.push(i)}),r===``)r+=[...this.symbolToInfo.entries()].filter(([e,t])=>t.count===1||e===`...`).map(([e])=>e).join(``);else if(!r.match(RegExp(lY)))throw Error(`Invalid RHS`);r.match(RegExp(cY,`g`))?.forEach(e=>{if(e===`...`)this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let t=this.symbolToInfo.get(e);if(t===void 0)throw Error(`Invalid RHS symbol`);this.outputDims.push(t.dimValue)}}),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(e,t,n){let r=this.symbolToInfo.get(e);if(r!==void 0){if(r.dimValue!==t&&r.count!==1)throw Error(`Dimension mismatch`);r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,r)}processTerm(e,t,n,r=-1){let i=n.length,a=!1,o=[],s=0;if(!e.match(RegExp(uY))&&!t&&e!==``)throw Error(`Invalid LHS term`);let c=e.match(RegExp(cY,`g`)),l=new pY(r);return c?.forEach((e,u)=>{if(e===`...`){if(a)throw Error(`Only one ellipsis is allowed per input term`);a=!0;let e=i-c.length+1;if(e<0)throw Error(`Ellipsis out of bounds`);if(o=n.slice(s,s+e),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw Error(`Ellipsis dimensions mismatch`)}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw Error(`Ellipsis must be specified in the LHS`);for(let e=0;e<o.length;e++){let t=String.fromCharCode(48+e);l.addSymbol(t,u+e),this.addSymbol(t,n[s++],r)}}else l.addSymbol(e,u+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(e,n[s++],r)}),l}},hY=e=>e+`_max`,gY=(e,t,n,r)=>{let i=e.map(e=>e.length).map((e,n)=>$(`input${n}`,t,e)),a=Q.size(r),o=XW(`output`,t,r.length),s=[...n.symbolToInfo.keys()].filter(e=>!n.rhs.symbolToIndices.has(e));return{name:`Einsum`,shaderCache:{hint:n.equation,inputDependencies:e.map(()=>`rank`)},getRunData:()=>{let i=s.filter(e=>n.symbolToInfo.has(e)).map(e=>({type:12,data:n.symbolToInfo.get(e)?.dimValue||0}));i.push({type:12,data:a});let o=e.map((e,t)=>[...UW(e)]).reduce((e,t)=>e.concat(t),i);return o.push(...UW(r)),{outputs:[{dims:r,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:o}},getShaderSource:e=>{let t=[],r=[],a=[],c=[],l=[],u=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach((e,s)=>{if(n.rhs.symbolToIndices.has(s)){let r=n.rhs.symbolToIndices.get(s)?.[0];r!==void 0&&n.lhs.forEach((n,a)=>{if(e.inputIndices.includes(a)){let e=n.symbolToIndices.get(s);if(e===void 0)throw Error(`Invalid symbol error`);e.forEach(e=>{t.push(`${i[a].indicesSet(`input${a}Indices`,e,o.indicesGet(`outputIndices`,r))}`)})}})}else n.lhs.forEach((t,n)=>{if(e.inputIndices.includes(n)){let e=t.symbolToIndices.get(s);if(e===void 0)throw Error(`Invalid symbol error`);e.forEach(e=>{r.push(`${i[n].indicesSet(`input${n}Indices`,e,`${s}`)}`)}),l.push(`prod *= ${i[n].getByIndices(`input${n}Indices`)};`)}}),a.push(`for(var ${s}: u32 = 0; ${s} < uniforms.${hY(s)}; ${s}++) {`),c.push(`}`)});let d=u?[...t,`let sum = ${i.map((e,t)=>e.getByIndices(`input${t}Indices`)).join(` * `)};`]:[...t,`var sum = 0.0;`,...a,...r,`var prod = 1.0;`,...l,`sum += prod;`,...c];return`
14146
+ ${e.registerUniforms(s.map(e=>({name:`${hY(e)}`,type:`u32`}))).registerUniform(`outputSize`,`u32`).declareVariables(...i,o)}
14147
14147
 
14148
14148
  ${e.mainStart()}
14149
14149
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.outputSize`)}
@@ -14153,7 +14153,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14153
14153
  ${d.join(`
14154
14154
  `)};
14155
14155
  ${o.setByOffset(`global_idx`,`sum`)};
14156
- }`}}},hY=(e,t)=>{let n=new fY(e.inputs,t.equation),r=n.outputDims,i=e.inputs.map((e,t)=>e.dims);e.compute(mY(i,e.inputs[0].dataType,n,r))},gY=e=>{let t=e.equation.replace(/\s+/g,``);return FW({equation:t})}}),vY,yY,bY,xY,SY,CY=Z(()=>{VU(),iW(),$W(),vY=e=>{if(!e||e.length!==2)throw Error(`Expand requires 2 input.`);let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=n.length<t.length?0:n.length-t.length,i=t.length<n.length?0:t.length-n.length;for(;r<n.length&&i<t.length;++r,++i)if(n[r]!==t[i]&&n[r]!==1&&t[i]!==1)throw Error(`Expand requires shape to be broadcastable to input`)},yY=(e,t)=>{let n=e.length-t.length,r=[];for(let t=0;t<n;++t)r.push(e[t]);for(let i=0;i<t.length;++i)r.push(t[i]===1?e[i+n]:t[i]);return r},bY=(e,t)=>e.length>t.length?yY(e,t):yY(t,e),xY=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=bY(t,n),i=e[0].dataType,a=i===9||Q.size(t)===1,o=i===9||t.length>0&&t[t.length-1]%4==0?4:1,s=a||r.length>0&&r[r.length-1]%4==0?4:1,c=Math.ceil(Q.size(r)/s),l=e=>{let n=$(`input`,i,t.length,o),a=JW(`output`,i,r.length,s),c;if(i===9){let e=(e,t,r=``)=>`
14156
+ }`}}},_Y=(e,t)=>{let n=new mY(e.inputs,t.equation),r=n.outputDims,i=e.inputs.map((e,t)=>e.dims);e.compute(gY(i,e.inputs[0].dataType,n,r))},vY=e=>{let t=e.equation.replace(/\s+/g,``);return LW({equation:t})}}),bY,xY,SY,CY,wY,TY=Z(()=>{UU(),oW(),tG(),bY=e=>{if(!e||e.length!==2)throw Error(`Expand requires 2 input.`);let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=n.length<t.length?0:n.length-t.length,i=t.length<n.length?0:t.length-n.length;for(;r<n.length&&i<t.length;++r,++i)if(n[r]!==t[i]&&n[r]!==1&&t[i]!==1)throw Error(`Expand requires shape to be broadcastable to input`)},xY=(e,t)=>{let n=e.length-t.length,r=[];for(let t=0;t<n;++t)r.push(e[t]);for(let i=0;i<t.length;++i)r.push(t[i]===1?e[i+n]:t[i]);return r},SY=(e,t)=>e.length>t.length?xY(e,t):xY(t,e),CY=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=SY(t,n),i=e[0].dataType,a=i===9||Q.size(t)===1,o=i===9||t.length>0&&t[t.length-1]%4==0?4:1,s=a||r.length>0&&r[r.length-1]%4==0?4:1,c=Math.ceil(Q.size(r)/s),l=e=>{let n=$(`input`,i,t.length,o),a=XW(`output`,i,r.length,s),c;if(i===9){let e=(e,t,r=``)=>`
14157
14157
  let outputIndices${t} = ${a.offsetToIndices(`outputOffset + ${t}u`)};
14158
14158
  let offset${t} = ${n.broadcastedIndicesToOffset(`outputIndices${t}`,a)};
14159
14159
  let index${t} = offset${t} / 4u;
@@ -14176,22 +14176,22 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14176
14176
  ${e.registerUniform(`vec_size`,`u32`).declareVariables(n,a)}
14177
14177
  ${e.mainStart()}
14178
14178
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.vec_size`)}
14179
- ${c}`},u=[{type:12,data:c},...VW(t,r)];return{name:`Expand`,shaderCache:{hint:`${r.length};${o}${s}`,inputDependencies:[`rank`]},getShaderSource:l,getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u})}},SY=e=>{vY(e.inputs),e.compute(xY(e.inputs),{inputs:[0]})}}),wY,TY,EY=Z(()=>{VU(),iW(),$W(),yq(),wY=e=>{let t=e[0].dataType,n=Q.size(e[0].dims),r=Q.size(e[1].dims),i=r%4==0;return{name:`FastGeluWithBias`,shaderCache:{hint:`${i}`,inputDependencies:[`type`,`type`]},getShaderSource:e=>{let n=$(`x`,t,[1],4),r=$(`bias`,t,[1],4),a=JW(`y`,t,[1],4),o=[{name:`output_vec_size`,type:`u32`},{name:`bias_size`,type:`u32`}],s=e=>`
14179
+ ${c}`},u=[{type:12,data:c},...UW(t,r)];return{name:`Expand`,shaderCache:{hint:`${r.length};${o}${s}`,inputDependencies:[`rank`]},getShaderSource:l,getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u})}},wY=e=>{bY(e.inputs),e.compute(CY(e.inputs),{inputs:[0]})}}),EY,DY,OY=Z(()=>{UU(),oW(),tG(),xq(),EY=e=>{let t=e[0].dataType,n=Q.size(e[0].dims),r=Q.size(e[1].dims),i=r%4==0;return{name:`FastGeluWithBias`,shaderCache:{hint:`${i}`,inputDependencies:[`type`,`type`]},getShaderSource:e=>{let n=$(`x`,t,[1],4),r=$(`bias`,t,[1],4),a=XW(`y`,t,[1],4),o=[{name:`output_vec_size`,type:`u32`},{name:`bias_size`,type:`u32`}],s=e=>`
14180
14180
  let bias${e}_offset: u32 = (global_idx * 4 + ${e}) % uniforms.bias_size;
14181
14181
  let bias${e} = ${r.getByOffset(`bias${e}_offset / 4`)}[bias${e}_offset % 4];`,c=i?`
14182
14182
  let bias = ${r.getByOffset(`global_idx % (uniforms.bias_size / 4)`)};`:`${s(0)}${s(1)}${s(2)}${s(3)}
14183
14183
  let bias = ${n.type.value}(bias0, bias1, bias2, bias3);`;return`${e.registerUniforms(o).declareVariables(n,r,a)}
14184
14184
 
14185
- ${dq(BW(t))}
14185
+ ${pq(HW(t))}
14186
14186
 
14187
- ${e.mainStart(LW)}
14187
+ ${e.mainStart(zW)}
14188
14188
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_vec_size`)}
14189
14189
 
14190
14190
  let x = ${n.getByOffset(`global_idx`)};
14191
14191
  ${c}
14192
14192
  let x_in = x + bias;
14193
- ${a.setByOffset(`global_idx`,fq(`x_in`))}
14194
- }`},getRunData:e=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/LW/4)}})}},TY=e=>{e.inputs.length<2||Q.size(e.inputs[1].dims)===0?pq(e):e.compute(wY(e.inputs))}}),DY,OY,kY,AY,jY=Z(()=>{VU(),iW(),IW(),$W(),DY=e=>{if(!e||e.length!==2)throw Error(`Gather requires 2 inputs.`)},OY=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Q.normalizeAxis(t.axis,i),o=n.slice(0);o.splice(a,1,...r);let s=n[a],c=e[0].dataType===9?4:1,l=Math.ceil(Q.size(o)/c),u=[{type:12,data:l},{type:6,data:s},{type:12,data:a},...VW(e[0].dims,e[1].dims,o)];return{name:`Gather`,shaderCache:{hint:t.cacheKey,inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:t=>{let n=$(`data`,e[0].dataType,e[0].dims.length,c),s=$(`inputIndices`,e[1].dataType,e[1].dims.length),l=JW(`output`,e[0].dataType,o.length,c),u=e=>{let t=r.length,c=`var indicesIndices${e} = ${s.type.indices}(0);`;for(let n=0;n<t;n++)c+=`${t>1?`indicesIndices${e}[${n}]`:`indicesIndices${e}`} = ${o.length>1?`outputIndices${e}[uniforms.axis + ${n}]`:`outputIndices${e}`};`;c+=`
14193
+ ${a.setByOffset(`global_idx`,mq(`x_in`))}
14194
+ }`},getRunData:e=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/zW/4)}})}},DY=e=>{e.inputs.length<2||Q.size(e.inputs[1].dims)===0?hq(e):e.compute(EY(e.inputs))}}),kY,AY,jY,MY,NY=Z(()=>{UU(),oW(),RW(),tG(),kY=e=>{if(!e||e.length!==2)throw Error(`Gather requires 2 inputs.`)},AY=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Q.normalizeAxis(t.axis,i),o=n.slice(0);o.splice(a,1,...r);let s=n[a],c=e[0].dataType===9?4:1,l=Math.ceil(Q.size(o)/c),u=[{type:12,data:l},{type:6,data:s},{type:12,data:a},...UW(e[0].dims,e[1].dims,o)];return{name:`Gather`,shaderCache:{hint:t.cacheKey,inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:t=>{let n=$(`data`,e[0].dataType,e[0].dims.length,c),s=$(`inputIndices`,e[1].dataType,e[1].dims.length),l=XW(`output`,e[0].dataType,o.length,c),u=e=>{let t=r.length,c=`var indicesIndices${e} = ${s.type.indices}(0);`;for(let n=0;n<t;n++)c+=`${t>1?`indicesIndices${e}[${n}]`:`indicesIndices${e}`} = ${o.length>1?`outputIndices${e}[uniforms.axis + ${n}]`:`outputIndices${e}`};`;c+=`
14195
14195
  var idx${e} = ${s.getByIndices(`indicesIndices${e}`)};
14196
14196
  if (idx${e} < 0) {
14197
14197
  idx${e} = idx${e} + uniforms.axisDimLimit;
@@ -14222,7 +14222,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14222
14222
  ${t.mainStart()}
14223
14223
  ${t.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.outputSize`)}
14224
14224
  ${d}
14225
- }`}}},kY=e=>FW({axis:e.axis}),AY=(e,t)=>{let n=e.inputs;DY(n),e.compute(OY(e.inputs,t))}}),MY,NY,PY,FY=Z(()=>{VU(),iW(),$W(),MY=(e,t,n,r,i,a,o,s,c)=>{let l=[{type:12,data:a},{type:12,data:r},{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:12,data:s},{type:12,data:c}],u=[a];return l.push(...VW(t.dims,u)),e.compute({name:`computeSliceOffsets`,shaderCache:{hint:`${i.length}_${n.length}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:u,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:e=>{let r=[$(`indices_data`,t.dataType,t.dims.length),JW(`input_slice_offsets_data`,12,1,1)],a=[{name:`output_size`,type:`u32`},{name:`batch_dims`,type:`u32`},{name:`input_dims`,type:`u32`,length:i.length},{name:`sizes_from_slice_dims_data`,type:`u32`,length:n.length},{name:`num_slices_per_batch`,type:`u32`},{name:`input_batch_stride`,type:`u32`},{name:`num_slice_dims`,type:`u32`}];return`
14225
+ }`}}},jY=e=>LW({axis:e.axis}),MY=(e,t)=>{let n=e.inputs;kY(n),e.compute(AY(e.inputs,t))}}),PY,FY,IY,LY=Z(()=>{UU(),oW(),tG(),PY=(e,t,n,r,i,a,o,s,c)=>{let l=[{type:12,data:a},{type:12,data:r},{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:12,data:s},{type:12,data:c}],u=[a];return l.push(...UW(t.dims,u)),e.compute({name:`computeSliceOffsets`,shaderCache:{hint:`${i.length}_${n.length}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:u,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:e=>{let r=[$(`indices_data`,t.dataType,t.dims.length),XW(`input_slice_offsets_data`,12,1,1)],a=[{name:`output_size`,type:`u32`},{name:`batch_dims`,type:`u32`},{name:`input_dims`,type:`u32`,length:i.length},{name:`sizes_from_slice_dims_data`,type:`u32`,length:n.length},{name:`num_slices_per_batch`,type:`u32`},{name:`input_batch_stride`,type:`u32`},{name:`num_slice_dims`,type:`u32`}];return`
14226
14226
  ${e.registerUniforms(a).declareVariables(...r)}
14227
14227
  ${e.mainStart()}
14228
14228
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -14241,13 +14241,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14241
14241
  }
14242
14242
 
14243
14243
  input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
14244
- }`}},{inputs:[t],outputs:[-1]})[0]},NY=(e,t)=>{let n=e.inputs,r=n[0].dims,i=n[0].dataType,a=n[1].dims,o=a[a.length-1],s=Q.sizeToDimension(a,a.length-1),c=Q.sizeFromDimension(r,t.batchDims+o),l=Q.sizeToDimension(r,t.batchDims),u=Q.sizeFromDimension(r,t.batchDims),d=s/l,f=Array(o),p=c;for(let e=0;e<o;++e)f[o-1-e]=p,p*=r[t.batchDims+o-1-e];let m=MY(e,n[1],f,t.batchDims,r,s,d,u,o),h=t.batchDims+o;if(h>r.length)throw Error(`last dimension of indices must not be larger than rank of input tensor`);let g=a.slice(0,-1).concat(r.slice(h)),_=Q.size(g),v=[{type:12,data:_},{type:12,data:c},...VW(n[0].dims,m.dims,g)];e.compute({name:`GatherND`,shaderCache:{hint:t.cacheKey,inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:g,dataType:i}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:e=>{let t=$(`data`,n[0].dataType,n[0].dims.length),r=$(`slice_offsets`,12,m.dims.length),i=JW(`output`,n[0].dataType,g.length);return`
14244
+ }`}},{inputs:[t],outputs:[-1]})[0]},FY=(e,t)=>{let n=e.inputs,r=n[0].dims,i=n[0].dataType,a=n[1].dims,o=a[a.length-1],s=Q.sizeToDimension(a,a.length-1),c=Q.sizeFromDimension(r,t.batchDims+o),l=Q.sizeToDimension(r,t.batchDims),u=Q.sizeFromDimension(r,t.batchDims),d=s/l,f=Array(o),p=c;for(let e=0;e<o;++e)f[o-1-e]=p,p*=r[t.batchDims+o-1-e];let m=PY(e,n[1],f,t.batchDims,r,s,d,u,o),h=t.batchDims+o;if(h>r.length)throw Error(`last dimension of indices must not be larger than rank of input tensor`);let g=a.slice(0,-1).concat(r.slice(h)),_=Q.size(g),v=[{type:12,data:_},{type:12,data:c},...UW(n[0].dims,m.dims,g)];e.compute({name:`GatherND`,shaderCache:{hint:t.cacheKey,inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:g,dataType:i}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:e=>{let t=$(`data`,n[0].dataType,n[0].dims.length),r=$(`slice_offsets`,12,m.dims.length),i=XW(`output`,n[0].dataType,g.length);return`
14245
14245
  ${e.registerUniform(`output_size`,`u32`).registerUniform(`slice_size`,`u32`).declareVariables(t,r,i)}
14246
14246
  ${e.mainStart()}
14247
14247
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
14248
14248
  let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
14249
14249
  output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
14250
- }`}},{inputs:[n[0],m]})},PY=e=>({batchDims:e.batch_dims,cacheKey:``})}),IY,LY,RY,zY,BY=Z(()=>{VU(),iW(),IW(),$W(),IY=(e,t)=>{if(e.length<3||e.length>4)throw Error(`GatherBlockQuantized requires 3 or 4 inputs.`);let n=Q.normalizeAxis(t.quantizeAxis,e[0].dims.length),r=t.blockSize,i=e[0],a=e[2],o=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map((e,t)=>t===n?Math.ceil(e/r)===a.dims[t]:e===a.dims[t]).reduce((e,t)=>e&&t,!0))throw Error(`Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.`);if(o){if(o.dataType!==i.dataType)throw Error(`Zero point must have the same data type as the input tensor.`);if(o.dims.length!==a.dims.length||!o.dims.map((e,t)=>e===a.dims[t]).reduce((e,t)=>e&&t,!0))throw Error(`Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.`)}},LY=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Q.normalizeAxis(t.gatherAxis,i),o=Q.normalizeAxis(t.quantizeAxis,i),s=n.slice(0);s.splice(a,1,...r);let c=Q.size(s),l=e[2].dataType,u=e[0].dataType===22,d=[{type:12,data:c},{type:12,data:o},{type:12,data:a},{type:12,data:t.blockSize},...VW(...e.map((e,t)=>e.dims),s)];return{name:`GatherBlockQuantized`,shaderCache:{hint:`${t.cacheKey};${e.filter((e,t)=>t!==1).map(e=>e.dims.join(`_`)).join(`;`)}`,inputDependencies:Array.from({length:e.length},(e,t)=>`rank`)},getRunData:()=>({outputs:[{dims:s,dataType:l}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:d}),getShaderSource:t=>{let i=$(`data`,e[0].dataType,e[0].dims.length),o=$(`inputIndices`,e[1].dataType,e[1].dims.length),c=$(`scales`,e[2].dataType,e[2].dims.length),d=e.length>3?$(`zeroPoint`,e[3].dataType,e[3].dims.length):void 0,f=JW(`output`,l,s.length),p=[i,o,c];return d&&p.push(d),`
14250
+ }`}},{inputs:[n[0],m]})},IY=e=>({batchDims:e.batch_dims,cacheKey:``})}),RY,zY,BY,VY,HY=Z(()=>{UU(),oW(),RW(),tG(),RY=(e,t)=>{if(e.length<3||e.length>4)throw Error(`GatherBlockQuantized requires 3 or 4 inputs.`);let n=Q.normalizeAxis(t.quantizeAxis,e[0].dims.length),r=t.blockSize,i=e[0],a=e[2],o=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map((e,t)=>t===n?Math.ceil(e/r)===a.dims[t]:e===a.dims[t]).reduce((e,t)=>e&&t,!0))throw Error(`Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.`);if(o){if(o.dataType!==i.dataType)throw Error(`Zero point must have the same data type as the input tensor.`);if(o.dims.length!==a.dims.length||!o.dims.map((e,t)=>e===a.dims[t]).reduce((e,t)=>e&&t,!0))throw Error(`Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.`)}},zY=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Q.normalizeAxis(t.gatherAxis,i),o=Q.normalizeAxis(t.quantizeAxis,i),s=n.slice(0);s.splice(a,1,...r);let c=Q.size(s),l=e[2].dataType,u=e[0].dataType===22,d=[{type:12,data:c},{type:12,data:o},{type:12,data:a},{type:12,data:t.blockSize},...UW(...e.map((e,t)=>e.dims),s)];return{name:`GatherBlockQuantized`,shaderCache:{hint:`${t.cacheKey};${e.filter((e,t)=>t!==1).map(e=>e.dims.join(`_`)).join(`;`)}`,inputDependencies:Array.from({length:e.length},(e,t)=>`rank`)},getRunData:()=>({outputs:[{dims:s,dataType:l}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:d}),getShaderSource:t=>{let i=$(`data`,e[0].dataType,e[0].dims.length),o=$(`inputIndices`,e[1].dataType,e[1].dims.length),c=$(`scales`,e[2].dataType,e[2].dims.length),d=e.length>3?$(`zeroPoint`,e[3].dataType,e[3].dims.length):void 0,f=XW(`output`,l,s.length),p=[i,o,c];return d&&p.push(d),`
14251
14251
  ${t.registerUniforms([{name:`output_size`,type:`u32`},{name:`quantize_axis`,type:`u32`},{name:`gather_axis`,type:`u32`},{name:`block_size`,type:`u32`}]).declareVariables(...p,f)}
14252
14252
  ${t.mainStart()}
14253
14253
  let output_indices = ${f.offsetToIndices(`global_idx`)};
@@ -14290,10 +14290,10 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14290
14290
  let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
14291
14291
  let zero_point_vec = ${u?`unpack4xI8`:`unpack4xU8`}(u32(packed_8bit_zero_points));
14292
14292
  let zero_point = zero_point_vec[zero_point_index / 2];`:`var zero_point = 0`};
14293
- let dequantized_data = ${BW(l)}(quantized_data - zero_point) * scale;
14293
+ let dequantized_data = ${HW(l)}(quantized_data - zero_point) * scale;
14294
14294
  ${f.setByOffset(`global_idx`,`dequantized_data`)};
14295
- }`}}},RY=(e,t)=>{let n=e.inputs;IY(n,t),e.compute(LY(e.inputs,t))},zY=e=>FW({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),VY,HY,UY,WY,GY=Z(()=>{VU(),iW(),IW(),$W(),VY=e=>{if(!e||e.length!==2)throw Error(`GatherElements requires 2 inputs.`);if(e[0].dims.length<1)throw Error(`GatherElements requires that the data input be rank >= 1.`);if(e[0].dims.length!==e[1].dims.length)throw Error(`GatherElements requires that the data input and
14296
- indices input tensors be of same rank.`)},HY=(e,t)=>{let n=e[0].dims,r=e[0].dataType,i=n.length,a=e[1].dims,o=e[1].dataType,s=Q.normalizeAxis(t.axis,i),c=n[s],l=a.slice(0),u=Q.size(l),d=$(`input`,r,i),f=$(`indicesInput`,o,a.length),p=JW(`output`,r,l.length),m=[{type:12,data:u},{type:6,data:c},{type:12,data:s}];return m.push(...VW(n,a,l)),{name:`GatherElements`,shaderCache:{inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:e=>`
14295
+ }`}}},BY=(e,t)=>{let n=e.inputs;RY(n,t),e.compute(zY(e.inputs,t))},VY=e=>LW({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),UY,WY,GY,KY,qY=Z(()=>{UU(),oW(),RW(),tG(),UY=e=>{if(!e||e.length!==2)throw Error(`GatherElements requires 2 inputs.`);if(e[0].dims.length<1)throw Error(`GatherElements requires that the data input be rank >= 1.`);if(e[0].dims.length!==e[1].dims.length)throw Error(`GatherElements requires that the data input and
14296
+ indices input tensors be of same rank.`)},WY=(e,t)=>{let n=e[0].dims,r=e[0].dataType,i=n.length,a=e[1].dims,o=e[1].dataType,s=Q.normalizeAxis(t.axis,i),c=n[s],l=a.slice(0),u=Q.size(l),d=$(`input`,r,i),f=$(`indicesInput`,o,a.length),p=XW(`output`,r,l.length),m=[{type:12,data:u},{type:6,data:c},{type:12,data:s}];return m.push(...UW(n,a,l)),{name:`GatherElements`,shaderCache:{inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:e=>`
14297
14297
  ${e.registerUniform(`outputSize`,`u32`).registerUniform(`axisDimLimit`,`i32`).registerUniform(`axis`,`u32`).declareVariables(d,f,p)}
14298
14298
  ${e.mainStart()}
14299
14299
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.outputSize`)}
@@ -14309,7 +14309,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14309
14309
  let value = ${d.getByIndices(`inputIndices`)};
14310
14310
 
14311
14311
  ${p.setByOffset(`global_idx`,`value`)};
14312
- }`}},UY=e=>FW({axis:e.axis}),WY=(e,t)=>{let n=e.inputs;VY(n),e.compute(HY(e.inputs,t))}}),KY,qY,JY,YY,XY=Z(()=>{VU(),iW(),$W(),KY=e=>{if(!e)throw Error(`Input is missing`);if(e.length<2||e.length>3)throw Error(`Invaid input number.`);if(e.length===3&&e[2].dims.length>2)throw Error(`Invalid input shape of C`);if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw Error(`Input types are mismatched`)},qY=(e,t)=>{let n=e[0].dims.slice(),r=e[1].dims.slice(),[i,a,o]=tW.getShapeOfGemmResult(n,t.transA,r,t.transB,e.length===3?e[2].dims:void 0),s=[i,a];if(!s)throw Error(`Can't use gemm on the given tensors`);let c=Math.ceil(a/16),l=Math.ceil(i/16);Q.size(s);let u=[{type:12,data:c},{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],d=[`type`,`type`];return e.length===3&&(u.push(...VW(e[2].dims)),d.push(`rank`)),u.push(...VW(s)),{name:`GemmShared`,shaderCache:{hint:`${t.cacheKey}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:c*l},programUniforms:u}),getShaderSource:n=>{let r=$(`a`,e[0].dataType,e[0].dims),i=$(`b`,e[1].dataType,e[1].dims),a=null,o=[r,i];e.length===3&&(a=$(`c`,e[2].dataType,e[2].dims.length),o.push(a));let c=JW(`output`,e[0].dataType,s.length);o.push(c);let l=[{name:`num_tile_n`,type:`u32`},{name:`M`,type:`u32`},{name:`N`,type:`u32`},{name:`K`,type:`u32`},{name:`alpha`,type:`f32`},{name:`beta`,type:`f32`}],u=``,d=``;t.transA&&t.transB?(d=`
14312
+ }`}},GY=e=>LW({axis:e.axis}),KY=(e,t)=>{let n=e.inputs;UY(n),e.compute(WY(e.inputs,t))}}),JY,YY,XY,ZY,QY=Z(()=>{UU(),oW(),tG(),JY=e=>{if(!e)throw Error(`Input is missing`);if(e.length<2||e.length>3)throw Error(`Invaid input number.`);if(e.length===3&&e[2].dims.length>2)throw Error(`Invalid input shape of C`);if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw Error(`Input types are mismatched`)},YY=(e,t)=>{let n=e[0].dims.slice(),r=e[1].dims.slice(),[i,a,o]=rW.getShapeOfGemmResult(n,t.transA,r,t.transB,e.length===3?e[2].dims:void 0),s=[i,a];if(!s)throw Error(`Can't use gemm on the given tensors`);let c=Math.ceil(a/16),l=Math.ceil(i/16);Q.size(s);let u=[{type:12,data:c},{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],d=[`type`,`type`];return e.length===3&&(u.push(...UW(e[2].dims)),d.push(`rank`)),u.push(...UW(s)),{name:`GemmShared`,shaderCache:{hint:`${t.cacheKey}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:c*l},programUniforms:u}),getShaderSource:n=>{let r=$(`a`,e[0].dataType,e[0].dims),i=$(`b`,e[1].dataType,e[1].dims),a=null,o=[r,i];e.length===3&&(a=$(`c`,e[2].dataType,e[2].dims.length),o.push(a));let c=XW(`output`,e[0].dataType,s.length);o.push(c);let l=[{name:`num_tile_n`,type:`u32`},{name:`M`,type:`u32`},{name:`N`,type:`u32`},{name:`K`,type:`u32`},{name:`alpha`,type:`f32`},{name:`beta`,type:`f32`}],u=``,d=``;t.transA&&t.transB?(d=`
14313
14313
  var col = tile_row_start + local_id.x;
14314
14314
  var row = k_start + local_id.y;
14315
14315
  if (col < uniforms.M && row < uniforms.K) {
@@ -14401,7 +14401,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14401
14401
  if (m < uniforms.M && n < uniforms.N) {
14402
14402
  output[m * uniforms.N + n] = value;
14403
14403
  }
14404
- }`}}},JY=e=>({transA:e.transA,transB:e.transB,alpha:e.alpha,beta:e.beta,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}),YY=(e,t)=>{KY(e.inputs),e.compute(qY(e.inputs,t))}}),ZY,QY,$Y,eX,tX,nX,rX,iX,aX,oX,sX,cX,lX,uX,dX=Z(()=>{VU(),iW(),IW(),$W(),[ZY,QY,$Y,eX]=[0,1,2,3],tX=e=>{if(e[0].dims.length!==4)throw Error(`only 4-D tensor is supported.`);if(e[0].dims.length!==e[1].dims.length)throw Error(`input dimensions must be equal to grid dimensions`);if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw Error(`grid batch size must match input batch size`)},nX=`
14404
+ }`}}},XY=e=>({transA:e.transA,transB:e.transB,alpha:e.alpha,beta:e.beta,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}),ZY=(e,t)=>{JY(e.inputs),e.compute(YY(e.inputs,t))}}),$Y,eX,tX,nX,rX,iX,aX,oX,sX,cX,lX,uX,dX,fX,pX=Z(()=>{UU(),oW(),RW(),tG(),[$Y,eX,tX,nX]=[0,1,2,3],rX=e=>{if(e[0].dims.length!==4)throw Error(`only 4-D tensor is supported.`);if(e[0].dims.length!==e[1].dims.length)throw Error(`input dimensions must be equal to grid dimensions`);if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw Error(`grid batch size must match input batch size`)},iX=`
14405
14405
  fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
14406
14406
  let cubic_alpha = -0.75f;
14407
14407
  let x_abs = abs(x);
@@ -14412,7 +14412,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14412
14412
  coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
14413
14413
  return coeffs;
14414
14414
  }
14415
- `,rX=e=>`
14415
+ `,aX=e=>`
14416
14416
  fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {
14417
14417
  var v: vec4<f32>;
14418
14418
  var coeffs = gs_get_cubic_coeffs(x);
@@ -14423,7 +14423,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14423
14423
  let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
14424
14424
  return pixel;
14425
14425
  }
14426
- `,iX=e=>`
14426
+ `,oX=e=>`
14427
14427
  fn gs_denormalize(n: f32, length: i32) -> f32 {
14428
14428
  ${e.alignCorners===0?`
14429
14429
  // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
@@ -14433,7 +14433,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14433
14433
  return (n + 1.0) / 2.0 * (f32(length - 1));
14434
14434
  `}
14435
14435
  }
14436
- `,aX=e=>`
14436
+ `,sX=e=>`
14437
14437
  ${e.paddingMode===`reflection`?`
14438
14438
  fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
14439
14439
  var dx = 0.0;
@@ -14460,39 +14460,39 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14460
14460
  }
14461
14461
  return u32(fx);
14462
14462
  }`:``}
14463
- `,oX=(e,t,n)=>`
14463
+ `,cX=(e,t,n)=>`
14464
14464
  fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {
14465
14465
  var pixel = ${t}(0);
14466
14466
  var indices = vec4<u32>(0);
14467
- indices[${ZY}] = batch;
14468
- indices[${QY}] = channel;`+(()=>{switch(n.paddingMode){case`zeros`:return`
14467
+ indices[${$Y}] = batch;
14468
+ indices[${eX}] = channel;`+(()=>{switch(n.paddingMode){case`zeros`:return`
14469
14469
  if (r >= 0 && r < H && c >=0 && c < W) {
14470
- indices[${$Y}] = u32(r);
14471
- indices[${eX}] = u32(c);
14470
+ indices[${tX}] = u32(r);
14471
+ indices[${nX}] = u32(c);
14472
14472
  } else {
14473
14473
  return ${t}(0);
14474
14474
  }
14475
14475
  `;case`border`:return`
14476
- indices[${$Y}] = u32(clamp(r, 0, H - 1));
14477
- indices[${eX}] = u32(clamp(c, 0, W - 1));
14476
+ indices[${tX}] = u32(clamp(r, 0, H - 1));
14477
+ indices[${nX}] = u32(clamp(c, 0, W - 1));
14478
14478
  `;case`reflection`:return`
14479
- indices[${$Y}] = gs_reflect(r, border[1], border[3]);
14480
- indices[${eX}] = gs_reflect(c, border[0], border[2]);
14479
+ indices[${tX}] = gs_reflect(r, border[1], border[3]);
14480
+ indices[${nX}] = gs_reflect(c, border[0], border[2]);
14481
14481
  `;default:throw Error(`padding mode ${n.paddingMode} is not supported`)}})()+`
14482
14482
  return ${e.getByIndices(`indices`)};
14483
14483
  }
14484
- `,sX=(e,t,n)=>(()=>{switch(n.mode){case`nearest`:return`
14485
- let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ZY}], indices[${QY}], border);
14484
+ `,lX=(e,t,n)=>(()=>{switch(n.mode){case`nearest`:return`
14485
+ let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${$Y}], indices[${eX}], border);
14486
14486
  `;case`bilinear`:return`
14487
14487
  let x1 = i32(floor(x));
14488
14488
  let y1 = i32(floor(y));
14489
14489
  let x2 = x1 + 1;
14490
14490
  let y2 = y1 + 1;
14491
14491
 
14492
- let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ZY}], indices[${QY}], border);
14493
- let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ZY}], indices[${QY}], border);
14494
- let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ZY}], indices[${QY}], border);
14495
- let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ZY}], indices[${QY}], border);
14492
+ let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${$Y}], indices[${eX}], border);
14493
+ let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${$Y}], indices[${eX}], border);
14494
+ let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${$Y}], indices[${eX}], border);
14495
+ let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${$Y}], indices[${eX}], border);
14496
14496
 
14497
14497
  let dx2 = ${t}(f32(x2) - x);
14498
14498
  let dx1 = ${t}(x - f32(x1));
@@ -14505,25 +14505,25 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14505
14505
  var p: mat4x4<${t}>;
14506
14506
  for (var h = 0; h < 4; h++) {
14507
14507
  for (var w = 0; w < 4; w++) {
14508
- p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ZY}], indices[${QY}], border);
14508
+ p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${$Y}], indices[${eX}], border);
14509
14509
  }
14510
14510
  }
14511
14511
 
14512
14512
  let dx = x - f32(x0 + 1);
14513
14513
  let dy = y - f32(y0 + 1);
14514
14514
  let result = gs_bicubic_interpolate(p, dx, dy);
14515
- `;default:throw Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset(`global_idx`,`result`)}`,cX=(e,t)=>{let n=$(`x`,e[0].dataType,e[0].dims.length),r=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=$(`grid`,e[1].dataType,r.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format===`NHWC`&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[ZY,QY,$Y,eX]=[0,3,1,2]);let o=JW(`output`,e[0].dataType,a.length),s=n.type.value,c=[{type:12,data:Q.size(a)},...VW(e[0].dims,r,a)];return{name:`GridSample`,shaderCache:{hint:`${t.cacheKey}`,inputDependencies:[`type`,`type`]},getRunData:e=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:c}},getShaderSource:e=>`
14515
+ `;default:throw Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset(`global_idx`,`result`)}`,uX=(e,t)=>{let n=$(`x`,e[0].dataType,e[0].dims.length),r=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=$(`grid`,e[1].dataType,r.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format===`NHWC`&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[$Y,eX,tX,nX]=[0,3,1,2]);let o=XW(`output`,e[0].dataType,a.length),s=n.type.value,c=[{type:12,data:Q.size(a)},...UW(e[0].dims,r,a)];return{name:`GridSample`,shaderCache:{hint:`${t.cacheKey}`,inputDependencies:[`type`,`type`]},getRunData:e=>{let t=Q.size(a);return{outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:c}},getShaderSource:e=>`
14516
14516
  ${e.registerUniform(`output_size`,`u32`).declareVariables(n,i,o)}
14517
- ${nX}
14518
- ${rX(s)}
14519
- ${iX(t)}
14520
- ${aX(t)}
14521
- ${oX(n,s,t)}
14517
+ ${iX}
14518
+ ${aX(s)}
14519
+ ${oX(t)}
14520
+ ${sX(t)}
14521
+ ${cX(n,s,t)}
14522
14522
 
14523
14523
  ${e.mainStart()}
14524
14524
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
14525
- let H_in = i32(uniforms.x_shape[${$Y}]);
14526
- let W_in = i32(uniforms.x_shape[${eX}]);
14525
+ let H_in = i32(uniforms.x_shape[${tX}]);
14526
+ let W_in = i32(uniforms.x_shape[${nX}]);
14527
14527
 
14528
14528
  ${t.alignCorners===0?`
14529
14529
  let x_min = -0.5;
@@ -14539,35 +14539,35 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
14539
14539
  let border = vec4<f32>(x_min, y_min, x_max, y_max);
14540
14540
 
14541
14541
  let indices = ${o.offsetToIndices(`global_idx`)};
14542
- var grid_indices = vec3<u32>(indices[${ZY}], indices[${$Y}], indices[${eX}]);
14542
+ var grid_indices = vec3<u32>(indices[${$Y}], indices[${tX}], indices[${nX}]);
14543
14543
  let nxy = ${i.getByIndices(`grid_indices`)};
14544
14544
  var x = gs_denormalize(f32(nxy[0]), W_in);
14545
14545
  var y = gs_denormalize(f32(nxy[1]), H_in);
14546
14546
 
14547
- ${sX(o,s,t)}
14548
- }`}},lX=(e,t)=>{tX(e.inputs),e.compute(cX(e.inputs,t))},uX=e=>FW({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),fX,pX,mX,hX,gX,_X,vX,yX=Z(()=>{VU(),iW(),IW(),CW(),vK(),$W(),lG(),fX=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,pX=(e,t)=>{let n=e[0],r=fX(e,1),i=fX(e,2),a=fX(e,3),o=fX(e,4),s=fX(e,5),c=fX(e,6),l=fX(e,7);if(n.dims.length!==3&&n.dims.length!==5)throw Error(`Input query is expected to have 3 or 5 dimensions`);let u=n.dims[0],d=n.dims[1],f=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],p=d,m=0,h=0,g=Math.floor(f/t.numHeads);if(c&&l&&Q.size(c.dims)&&Q.size(l.dims)){if(c.dims.length!==4)throw Error(`Input "past_key" is expected to have 4 dimensions`);if(c.dims[0]!==u||c.dims[1]!==t.numHeads||c.dims[3]!==g)throw Error(`Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)`);if(l.dims[0]!==u||l.dims[1]!==t.numHeads||l.dims[3]!==g)throw Error(`Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)`);if(c.dims[2]!==l.dims[2])throw Error(`Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)`);if(l.dims.length!==4)throw Error(`Input "past_value" is expected to have 4 dimensions`);m=c.dims[2],h=c.dims[2]}else if(c&&Q.size(c.dims)||l&&Q.size(l.dims))throw Error(`Input "past_key" and "past_value" shall be both present or both absent`);let _;if(r&&Q.size(r.dims)>0){if(n.dims.length!==3)throw Error(`Input "query" is expected to have 3 dimensions when key is given`);if(r.dims.length<3||r.dims.length>5)throw Error(`Input "key" is expected to have 3, 4, or 5 dimensions`);if(n.dims[0]!==r.dims[0])throw Error(`Input "query" and "key" shall have same dim 0 (batch size)`);if(r.dims.length===3){if(r.dims[2]!==n.dims[2])throw Error(`Input "query" and "key" shall have same dim 2 (hidden_size)`);_=2,p=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==t.numHeads||r.dims[3]!==2||r.dims[4]!==g)throw Error(`Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv`);if(i)throw Error(`Expect "value" be none when "key" has packed kv format.`);_=5,p=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==g)throw Error(`Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key`);_=0,p=r.dims[2]}}else{if(n.dims.length!==5)throw Error(`Input "query" is expected to have 5 dimensions when key is empty`);if(n.dims[2]!==t.numHeads||n.dims[3]!==3)throw Error(`Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv`);_=3}if(a&&Q.size(a.dims)>0){if(a.dims.length!==1)throw Error(`Input "bias" is expected to have 1 dimension`);if(r&&r.dims.length===5&&r.dims[3]===2)throw Error(`bias is not allowed for packed kv.`)}let v=m+p,y=0;if(o&&Q.size(o.dims)>0){y=8;let e=o.dims;throw e.length===1?e[0]===u?y=1:e[0]===3*u+2&&(y=3):e.length===2&&e[0]===u&&e[1]===v&&(y=5),Error(y===8?`Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)`:`Mask not supported`)}let b=!1,x=f;if(i&&Q.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw Error(`Input "value" is expected to have 3 or 4 dimensions`);if(n.dims[0]!==i.dims[0])throw Error(`Input "query" and "value" shall have same dim 0 (batch_size)`);if(i.dims.length===3){if(p!==i.dims[1])throw Error(`Input "key" and "value" shall have the same dim 1 (kv_sequence_length)`);x=i.dims[2]}else{if(p!==i.dims[2])throw Error(`Input "key" and "value" shall have the same dim 2 (kv_sequence_length)`);x=i.dims[1]*i.dims[3],b=!0}}if(o&&Q.size(o.dims)>0)throw Error(`Key padding mask is not supported`);if(s&&Q.size(s.dims)>0){if(s.dims.length!==4)throw Error(`Input "attention_bias" is expected to have 4 dimensions`);if(s.dims[0]!==u||s.dims[1]!==t.numHeads||s.dims[2]!==d||s.dims[3]!==v)throw Error(`Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)`)}return{batchSize:u,sequenceLength:d,pastSequenceLength:m,kvSequenceLength:p,totalSequenceLength:v,maxSequenceLength:h,inputHiddenSize:0,hiddenSize:f,vHiddenSize:x,headSize:g,vHeadSize:Math.floor(x/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:y,scale:t.scale,broadcastResPosBias:!1,passPastInKv:b,qkvFormat:_}},mX=e=>FW({...e}),hX=FW({perm:[0,2,1,3]}),gX=(e,t,n,r,i,a,o)=>{let s=[r,i,a],c=Q.size(s),l=[{type:12,data:c},{type:12,data:o},{type:12,data:a}];return e.compute({name:`MultiHeadAttentionAddBias`,shaderCache:{inputDependencies:[`type`,`type`]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:l}),getShaderSource:e=>{let r=JW(`qkv_with_bias`,t.dataType,s),i=$(`qkv`,t.dataType,s),a=$(`bias`,n.dataType,s);return`
14547
+ ${lX(o,s,t)}
14548
+ }`}},dX=(e,t)=>{rX(e.inputs),e.compute(uX(e.inputs,t))},fX=e=>LW({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),mX,hX,gX,_X,vX,yX,bX,xX=Z(()=>{UU(),oW(),RW(),TW(),bK(),tG(),dG(),mX=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,hX=(e,t)=>{let n=e[0],r=mX(e,1),i=mX(e,2),a=mX(e,3),o=mX(e,4),s=mX(e,5),c=mX(e,6),l=mX(e,7);if(n.dims.length!==3&&n.dims.length!==5)throw Error(`Input query is expected to have 3 or 5 dimensions`);let u=n.dims[0],d=n.dims[1],f=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],p=d,m=0,h=0,g=Math.floor(f/t.numHeads);if(c&&l&&Q.size(c.dims)&&Q.size(l.dims)){if(c.dims.length!==4)throw Error(`Input "past_key" is expected to have 4 dimensions`);if(c.dims[0]!==u||c.dims[1]!==t.numHeads||c.dims[3]!==g)throw Error(`Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)`);if(l.dims[0]!==u||l.dims[1]!==t.numHeads||l.dims[3]!==g)throw Error(`Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)`);if(c.dims[2]!==l.dims[2])throw Error(`Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)`);if(l.dims.length!==4)throw Error(`Input "past_value" is expected to have 4 dimensions`);m=c.dims[2],h=c.dims[2]}else if(c&&Q.size(c.dims)||l&&Q.size(l.dims))throw Error(`Input "past_key" and "past_value" shall be both present or both absent`);let _;if(r&&Q.size(r.dims)>0){if(n.dims.length!==3)throw Error(`Input "query" is expected to have 3 dimensions when key is given`);if(r.dims.length<3||r.dims.length>5)throw Error(`Input "key" is expected to have 3, 4, or 5 dimensions`);if(n.dims[0]!==r.dims[0])throw Error(`Input "query" and "key" shall have same dim 0 (batch size)`);if(r.dims.length===3){if(r.dims[2]!==n.dims[2])throw Error(`Input "query" and "key" shall have same dim 2 (hidden_size)`);_=2,p=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==t.numHeads||r.dims[3]!==2||r.dims[4]!==g)throw Error(`Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv`);if(i)throw Error(`Expect "value" be none when "key" has packed kv format.`);_=5,p=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==g)throw Error(`Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key`);_=0,p=r.dims[2]}}else{if(n.dims.length!==5)throw Error(`Input "query" is expected to have 5 dimensions when key is empty`);if(n.dims[2]!==t.numHeads||n.dims[3]!==3)throw Error(`Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv`);_=3}if(a&&Q.size(a.dims)>0){if(a.dims.length!==1)throw Error(`Input "bias" is expected to have 1 dimension`);if(r&&r.dims.length===5&&r.dims[3]===2)throw Error(`bias is not allowed for packed kv.`)}let v=m+p,y=0;if(o&&Q.size(o.dims)>0){y=8;let e=o.dims;throw e.length===1?e[0]===u?y=1:e[0]===3*u+2&&(y=3):e.length===2&&e[0]===u&&e[1]===v&&(y=5),Error(y===8?`Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)`:`Mask not supported`)}let b=!1,x=f;if(i&&Q.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw Error(`Input "value" is expected to have 3 or 4 dimensions`);if(n.dims[0]!==i.dims[0])throw Error(`Input "query" and "value" shall have same dim 0 (batch_size)`);if(i.dims.length===3){if(p!==i.dims[1])throw Error(`Input "key" and "value" shall have the same dim 1 (kv_sequence_length)`);x=i.dims[2]}else{if(p!==i.dims[2])throw Error(`Input "key" and "value" shall have the same dim 2 (kv_sequence_length)`);x=i.dims[1]*i.dims[3],b=!0}}if(o&&Q.size(o.dims)>0)throw Error(`Key padding mask is not supported`);if(s&&Q.size(s.dims)>0){if(s.dims.length!==4)throw Error(`Input "attention_bias" is expected to have 4 dimensions`);if(s.dims[0]!==u||s.dims[1]!==t.numHeads||s.dims[2]!==d||s.dims[3]!==v)throw Error(`Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)`)}return{batchSize:u,sequenceLength:d,pastSequenceLength:m,kvSequenceLength:p,totalSequenceLength:v,maxSequenceLength:h,inputHiddenSize:0,hiddenSize:f,vHiddenSize:x,headSize:g,vHeadSize:Math.floor(x/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:y,scale:t.scale,broadcastResPosBias:!1,passPastInKv:b,qkvFormat:_}},gX=e=>LW({...e}),_X=LW({perm:[0,2,1,3]}),vX=(e,t,n,r,i,a,o)=>{let s=[r,i,a],c=Q.size(s),l=[{type:12,data:c},{type:12,data:o},{type:12,data:a}];return e.compute({name:`MultiHeadAttentionAddBias`,shaderCache:{inputDependencies:[`type`,`type`]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:l}),getShaderSource:e=>{let r=XW(`qkv_with_bias`,t.dataType,s),i=$(`qkv`,t.dataType,s),a=$(`bias`,n.dataType,s);return`
14549
14549
  ${e.registerUniforms([{name:`output_size`,type:`u32`},{name:`bias_offset`,type:`u32`},{name:`hidden_size`,type:`u32`}]).declareVariables(i,a,r)}
14550
14550
  ${e.mainStart()}
14551
14551
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
14552
14552
  let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
14553
14553
 
14554
14554
  qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
14555
- }`}},{inputs:[t,n],outputs:[-1]})[0]},_X=(e,t,n,r,i,a,o,s)=>{let c=a;if(o&&Q.size(o.dims)>0){if(r===1)throw Error(`AddBiasReshape is not implemented. Please export your model with packed QKV or KV`);return c=gX(e,a,o,t,r,n*i,s),c=c.reshape([t,r,n,i]),n===1||r===1?c:e.compute(oG(c,hX.perm),{inputs:[c],outputs:[-1]})[0]}else return a.dims.length===3&&(c=a.reshape([t,r,n,i])),n===1||r===1?c:e.compute(oG(c,hX.perm),{inputs:[c],outputs:[-1]})[0]},vX=(e,t)=>{let n=pX(e.inputs,t),r=e.inputs[0],i=fX(e.inputs,1),a=fX(e.inputs,2),o=fX(e.inputs,3),s=fX(e.inputs,4),c=fX(e.inputs,5),l=fX(e.inputs,6),u=fX(e.inputs,7);if(r.dims.length===5)throw Error(`Packed QKV is not implemented`);if(i?.dims.length===5)throw Error(`Packed KV is not implemented`);let d=i&&a&&i.dims.length===4&&a.dims.length===4,f=_X(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,o,0);if(d)return hK(e,f,i,a,s,void 0,l,u,c,n);if(!i||!a)throw Error(`key and value must be provided`);let p=_X(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,i,o,n.hiddenSize),m=_X(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,a,o,2*n.hiddenSize);hK(e,f,p,m,s,void 0,l,u,c,n)}}),bX,xX,SX,CX,wX,TX,EX,DX=Z(()=>{VU(),iW(),IW(),$W(),bX=e=>{if(!e||e.length<1)throw Error(`too few inputs`)},xX=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(e=>n.push(Number(e))),r=n.length),FW({numOutputs:r,axis:t.axis,splitSizes:n})},SX=e=>`
14555
+ }`}},{inputs:[t,n],outputs:[-1]})[0]},yX=(e,t,n,r,i,a,o,s)=>{let c=a;if(o&&Q.size(o.dims)>0){if(r===1)throw Error(`AddBiasReshape is not implemented. Please export your model with packed QKV or KV`);return c=vX(e,a,o,t,r,n*i,s),c=c.reshape([t,r,n,i]),n===1||r===1?c:e.compute(cG(c,_X.perm),{inputs:[c],outputs:[-1]})[0]}else return a.dims.length===3&&(c=a.reshape([t,r,n,i])),n===1||r===1?c:e.compute(cG(c,_X.perm),{inputs:[c],outputs:[-1]})[0]},bX=(e,t)=>{let n=hX(e.inputs,t),r=e.inputs[0],i=mX(e.inputs,1),a=mX(e.inputs,2),o=mX(e.inputs,3),s=mX(e.inputs,4),c=mX(e.inputs,5),l=mX(e.inputs,6),u=mX(e.inputs,7);if(r.dims.length===5)throw Error(`Packed QKV is not implemented`);if(i?.dims.length===5)throw Error(`Packed KV is not implemented`);let d=i&&a&&i.dims.length===4&&a.dims.length===4,f=yX(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,o,0);if(d)return _K(e,f,i,a,s,void 0,l,u,c,n);if(!i||!a)throw Error(`key and value must be provided`);let p=yX(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,i,o,n.hiddenSize),m=yX(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,a,o,2*n.hiddenSize);_K(e,f,p,m,s,void 0,l,u,c,n)}}),SX,CX,wX,TX,EX,DX,OX,kX=Z(()=>{UU(),oW(),RW(),tG(),SX=e=>{if(!e||e.length<1)throw Error(`too few inputs`)},CX=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(e=>n.push(Number(e))),r=n.length),LW({numOutputs:r,axis:t.axis,splitSizes:n})},wX=e=>`
14556
14556
  fn calculateOutputIndex(index: u32) -> u32 {
14557
14557
  for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
14558
- if (index < ${KW(`uniforms.size_in_split_axis`,`i`,e)}) {
14558
+ if (index < ${JW(`uniforms.size_in_split_axis`,`i`,e)}) {
14559
14559
  return i;
14560
14560
  }
14561
14561
  }
14562
14562
  return ${e}u;
14563
- }`,CX=e=>{let t=e.length,n=[];for(let r=0;r<t;++r){let i=e[r].setByIndices(`indices`,`input[global_idx]`);t===1?n.push(i):r===0?n.push(`if (output_number == ${r}u) { ${i} }`):r===t-1?n.push(`else { ${i} }`):n.push(`else if (output_number == ${r}) { ${i} }`)}return`
14563
+ }`,TX=e=>{let t=e.length,n=[];for(let r=0;r<t;++r){let i=e[r].setByIndices(`indices`,`input[global_idx]`);t===1?n.push(i):r===0?n.push(`if (output_number == ${r}u) { ${i} }`):r===t-1?n.push(`else { ${i} }`):n.push(`else if (output_number == ${r}) { ${i} }`)}return`
14564
14564
  fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
14565
14565
  ${n.join(`
14566
14566
  `)}
14567
- }`},wX=(e,t)=>{let n=e[0].dims,r=Q.size(n),i=e[0].dataType,a=Q.normalizeAxis(t.axis,n.length),o=Array(t.numOutputs),s=$(`input`,i,n.length),c=Array(t.numOutputs),l=[],u=[],d=0,f=[{type:12,data:r}];for(let r=0;r<t.numOutputs;r++){d+=t.splitSizes[r],c[r]=d;let s=n.slice();s[a]=t.splitSizes[r],u.push(s),o[r]=JW(`output${r}`,i,s.length),l.push({dims:u[r],dataType:e[0].dataType})}return f.push({type:12,data:c},...VW(n,...u)),{name:`Split`,shaderCache:{hint:t.cacheKey,inputDependencies:[`rank`]},getShaderSource:e=>`
14567
+ }`},EX=(e,t)=>{let n=e[0].dims,r=Q.size(n),i=e[0].dataType,a=Q.normalizeAxis(t.axis,n.length),o=Array(t.numOutputs),s=$(`input`,i,n.length),c=Array(t.numOutputs),l=[],u=[],d=0,f=[{type:12,data:r}];for(let r=0;r<t.numOutputs;r++){d+=t.splitSizes[r],c[r]=d;let s=n.slice();s[a]=t.splitSizes[r],u.push(s),o[r]=XW(`output${r}`,i,s.length),l.push({dims:u[r],dataType:e[0].dataType})}return f.push({type:12,data:c},...UW(n,...u)),{name:`Split`,shaderCache:{hint:t.cacheKey,inputDependencies:[`rank`]},getShaderSource:e=>`
14568
14568
  ${e.registerUniform(`input_size`,`u32`).registerUniform(`size_in_split_axis`,`u32`,c.length).declareVariables(s,...o)}
14569
- ${SX(c.length)}
14570
- ${CX(o)}
14569
+ ${wX(c.length)}
14570
+ ${TX(o)}
14571
14571
 
14572
14572
  ${e.mainStart()}
14573
14573
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.input_size`)}
@@ -14576,14 +14576,14 @@ fn calculateOutputIndex(index: u32) -> u32 {
14576
14576
  var index = ${s.indicesGet(`indices`,a)};
14577
14577
  let output_number = calculateOutputIndex(index);
14578
14578
  if (output_number != 0) {
14579
- index -= ${KW(`uniforms.size_in_split_axis`,`output_number - 1u`,c.length)};
14579
+ index -= ${JW(`uniforms.size_in_split_axis`,`output_number - 1u`,c.length)};
14580
14580
  ${s.indicesSet(`indices`,a,`index`)};
14581
14581
  }
14582
14582
  writeBufferData(output_number, indices, global_idx);
14583
- }`,getRunData:()=>({outputs:l,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:f})}},TX=(e,t)=>{bX(e.inputs);let n=e.inputs.length===1?t:xX(e.inputs,t);e.compute(wX(e.inputs,n),{inputs:[0]})},EX=e=>{let t=e.axis,n=e.splitSizes,r=e.numOutputs<0?n.length:e.numOutputs;if(r!==n.length)throw Error(`numOutputs and splitSizes length must be equal`);return FW({axis:t,numOutputs:r,splitSizes:n})}}),OX,kX,AX,jX=Z(()=>{VU(),iW(),IW(),$W(),OX=(e,t)=>{let[n,r,i,a]=e,{numHeads:o,rotaryEmbeddingDim:s}=t;if(n.dims.length!==3&&n.dims.length!==4)throw Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!Q.areEqual(r.dims,[])&&!Q.areEqual(r.dims,[1])&&r.dims.length!==2)throw Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${r.dims.length}`);if(i.dims.length!==2)throw Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Q.areEqual(i.dims,a.dims))throw Error(`Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape`);if(s>0&&o===0)throw Error(`num_heads must be provided if rotary_embedding_dim is specified`);let c=n.dims[0],l=n.dims[n.dims.length-2],u=i.dims[0],d=Q.sizeFromDimension(n.dims,1)/l,f=s===0?i.dims[1]*2:d/o;if(s>f)throw Error(`rotary_embedding_dim must be less than or equal to head_size`);if(r.dims.length===2){if(c!==r.dims[0])throw Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${r.dims[0]}`);if(l!==r.dims[1])throw Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${r.dims[1]}`)}if(f/2!==i.dims[1]&&s/2!==i.dims[1])throw Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(l>u)throw Error(`Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported`)},kX=(e,t)=>{let{interleaved:n,numHeads:r,rotaryEmbeddingDim:i,scale:a}=t,o=e[0].dims[0],s=Q.sizeFromDimension(e[0].dims,1),c=e[0].dims[e[0].dims.length-2],l=s/c,u=e[2].dims[1],d=i===0?u*2:l/r,f=[o,c,l/d,d-u],p=Q.computeStrides(f),m=[{type:1,data:a},{type:12,data:f},{type:12,data:p},...e[0].dims.length===3?Array({type:12,data:[s,l,d,1]}):[],...e[0].dims.length===4?Array({type:12,data:[s,d,c*d,1]}):[],...VW(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)];return{name:`RotaryEmbedding`,shaderCache:{hint:FW({interleaved:n}).cacheKey,inputDependencies:[`rank`,`rank`,`rank`,`rank`]},getShaderSource:t=>{let r=$(`input`,e[0].dataType,e[0].dims.length),i=$(`position_ids`,e[1].dataType,e[1].dims.length),a=$(`cos_cache`,e[2].dataType,e[2].dims.length),o=$(`sin_cache`,e[3].dataType,e[3].dims.length),s=JW(`output`,e[0].dataType,e[0].dims.length);return t.registerUniforms([{name:`scale`,type:`f32`},{name:`global_shape`,type:`u32`,length:f.length},{name:`global_strides`,type:`u32`,length:p.length},{name:`input_output_strides`,type:`u32`,length:p.length}]),`
14583
+ }`,getRunData:()=>({outputs:l,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:f})}},DX=(e,t)=>{SX(e.inputs);let n=e.inputs.length===1?t:CX(e.inputs,t);e.compute(EX(e.inputs,n),{inputs:[0]})},OX=e=>{let t=e.axis,n=e.splitSizes,r=e.numOutputs<0?n.length:e.numOutputs;if(r!==n.length)throw Error(`numOutputs and splitSizes length must be equal`);return LW({axis:t,numOutputs:r,splitSizes:n})}}),AX,jX,MX,NX=Z(()=>{UU(),oW(),RW(),tG(),AX=(e,t)=>{let[n,r,i,a]=e,{numHeads:o,rotaryEmbeddingDim:s}=t;if(n.dims.length!==3&&n.dims.length!==4)throw Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!Q.areEqual(r.dims,[])&&!Q.areEqual(r.dims,[1])&&r.dims.length!==2)throw Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${r.dims.length}`);if(i.dims.length!==2)throw Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Q.areEqual(i.dims,a.dims))throw Error(`Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape`);if(s>0&&o===0)throw Error(`num_heads must be provided if rotary_embedding_dim is specified`);let c=n.dims[0],l=n.dims[n.dims.length-2],u=i.dims[0],d=Q.sizeFromDimension(n.dims,1)/l,f=s===0?i.dims[1]*2:d/o;if(s>f)throw Error(`rotary_embedding_dim must be less than or equal to head_size`);if(r.dims.length===2){if(c!==r.dims[0])throw Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${r.dims[0]}`);if(l!==r.dims[1])throw Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${r.dims[1]}`)}if(f/2!==i.dims[1]&&s/2!==i.dims[1])throw Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(l>u)throw Error(`Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported`)},jX=(e,t)=>{let{interleaved:n,numHeads:r,rotaryEmbeddingDim:i,scale:a}=t,o=e[0].dims[0],s=Q.sizeFromDimension(e[0].dims,1),c=e[0].dims[e[0].dims.length-2],l=s/c,u=e[2].dims[1],d=i===0?u*2:l/r,f=[o,c,l/d,d-u],p=Q.computeStrides(f),m=[{type:1,data:a},{type:12,data:f},{type:12,data:p},...e[0].dims.length===3?Array({type:12,data:[s,l,d,1]}):[],...e[0].dims.length===4?Array({type:12,data:[s,d,c*d,1]}):[],...UW(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)];return{name:`RotaryEmbedding`,shaderCache:{hint:LW({interleaved:n}).cacheKey,inputDependencies:[`rank`,`rank`,`rank`,`rank`]},getShaderSource:t=>{let r=$(`input`,e[0].dataType,e[0].dims.length),i=$(`position_ids`,e[1].dataType,e[1].dims.length),a=$(`cos_cache`,e[2].dataType,e[2].dims.length),o=$(`sin_cache`,e[3].dataType,e[3].dims.length),s=XW(`output`,e[0].dataType,e[0].dims.length);return t.registerUniforms([{name:`scale`,type:`f32`},{name:`global_shape`,type:`u32`,length:f.length},{name:`global_strides`,type:`u32`,length:p.length},{name:`input_output_strides`,type:`u32`,length:p.length}]),`
14584
14584
  ${t.declareVariables(r,i,a,o,s)}
14585
14585
 
14586
- ${t.mainStart(LW)}
14586
+ ${t.mainStart(zW)}
14587
14587
  let half_rotary_emb_dim = uniforms.${a.name}_shape[1];
14588
14588
  let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
14589
14589
  let size = uniforms.global_shape[0] * uniforms.global_strides[0];
@@ -14591,7 +14591,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
14591
14591
 
14592
14592
  if (bsnh[3] < half_rotary_emb_dim) {
14593
14593
  let position_ids_idx =
14594
- ${i.broadcastedIndicesToOffset(`bsnh.xy`,JW(``,i.type.tensor,2))};
14594
+ ${i.broadcastedIndicesToOffset(`bsnh.xy`,XW(``,i.type.tensor,2))};
14595
14595
  let position_id =
14596
14596
  u32(${i.getByOffset(`position_ids_idx`)}) + select(0, bsnh[1], position_ids_idx == 0);
14597
14597
  let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n});
@@ -14606,7 +14606,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
14606
14606
  let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
14607
14607
  ${s.setByOffset(`k`,r.getByOffset(`k`))}
14608
14608
  }
14609
- }`},getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Q.size(f)/LW)},programUniforms:m})}},AX=(e,t)=>{OX(e.inputs,t),e.compute(kX(e.inputs,t))}}),MX,NX,PX,FX,IX,LX=Z(()=>{IW(),VU(),vK(),yX(),DX(),lG(),jX(),$W(),MX=(e,t)=>{if(t.doRotary&&e.length<=7)throw Error(`cos_cache and sin_cache inputs are required if do_rotary is specified`);let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4];if(t.doRotary!==0&&e.length<=7)throw Error(`cos_cast and sin_cache are expected if do_rotary attribute is non-zero`);if(t.localWindowSize!==-1)throw Error(`Local attention is not supported`);if(t.softcap!==0)throw Error(`Softcap is not supported`);if(t.rotaryInterleaved!==0)throw Error(`Rotary interleaved is not supported`);if(t.smoothSoftmax)throw Error(`Smooth softmax is not supported`);if(n.dims.length!==3&&n.dims.length!==5)throw Error(`Input query is expected to have 3 or 5 dimensions`);let s=n.dims[0],c=n.dims[1],l=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],u=c,d=0,f=!r||r.dims.length===0,p=Math.floor(f?l/(t.numHeads+2*t.kvNumHeads):l/t.numHeads);f&&(l=p*t.numHeads);let m=a&&a.dims.length!==0,h=o&&o.dims.length!==0;if(m&&a.dims.length===4&&a.dims[0]===s&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===p)throw Error(`BSNH pastKey/pastValue is not supported`);if(m&&h){if(a.dims.length!==4)throw Error(`Input "past_key" is expected to have 4 dimensions`);if(o.dims.length!==4)throw Error(`Input "past_value" is expected to have 4 dimensions`);d=a.dims[2]}else if(m||h)throw Error(`Input "past_key" and "past_value" shall be both present or both absent`);let g=1;if(r&&r.dims.length>0){if(n.dims.length!==3)throw Error(`Input "query" is expected to have 3 dimensions when key is given`);if(r.dims.length<3||r.dims.length>5)throw Error(`Input "key" is expected to have 3, 4, or 5 dimensions`);if(n.dims[0]!==r.dims[0])throw Error(`Input "query" and "key" shall have same dim 0 (batch size)`);if(r.dims.length===3){if(n.dims[2]%r.dims[2]!==0)throw Error(`Dimension 2 of "query" should be a multiple of "key"`);u=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==t.numHeads||r.dims[3]!==2||r.dims[4]!==p)throw Error(`Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv`);if(i)throw Error(`Expect "value" be none when "key" has packed kv format.`);u=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==p)throw Error(`Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key`);u=r.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw Error(`Input "query" is expected to have 3 or 5 dimensions when key is empty`);if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw Error(`Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv`);g=3}let _=!1,v=t.kvNumHeads?p*t.kvNumHeads:l;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw Error(`Input "value" is expected to have 3 or 4 dimensions`);if(n.dims[0]!==i.dims[0])throw Error(`Input "query" and "value" shall have same dim 0 (batch_size)`);if(i.dims.length===3){if(u!==i.dims[1])throw Error(`Input "key" and "value" shall have the same dim 1 (kv_sequence_length)`);v=i.dims[2]}else{if(u!==i.dims[2])throw Error(`Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)`);v=i.dims[1]*i.dims[3],_=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.dims[0]!==s)throw Error(`Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size`);return{batchSize:s,sequenceLength:c,pastSequenceLength:d,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:l,vHiddenSize:v,headSize:p,vHeadSize:Math.floor(v/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_,qkvFormat:g}},NX=FW({perm:[0,2,1,3]}),PX=(e,t,n)=>{let r=t,i=n.kvNumHeads;return t.dims.length===3&&n.kvSequenceLength!==0&&(r=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize]),r=e.compute(oG(r,NX.perm),{inputs:[r],outputs:[-1]})[0]),r},FX=(e,t,n,r)=>{let i=[`type`,`type`],a=[e*t],o=e*t,s=[{type:12,data:o},{type:12,data:t},{type:12,data:e}];return{name:`GeneratePositionIds`,shaderCache:{hint:`${e};${t}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:a,dataType:7}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:s}),getShaderSource:e=>{let t=$(`seq_lens`,n.dataType,n.dims),i=$(`total_seq_lens`,r.dataType,r.dims),o=JW(`pos_ids`,7,a);return`
14609
+ }`},getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Q.size(f)/zW)},programUniforms:m})}},MX=(e,t)=>{AX(e.inputs,t),e.compute(jX(e.inputs,t))}}),PX,FX,IX,LX,RX,zX=Z(()=>{RW(),UU(),bK(),xX(),kX(),dG(),NX(),tG(),PX=(e,t)=>{if(t.doRotary&&e.length<=7)throw Error(`cos_cache and sin_cache inputs are required if do_rotary is specified`);let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4];if(t.doRotary!==0&&e.length<=7)throw Error(`cos_cast and sin_cache are expected if do_rotary attribute is non-zero`);if(t.localWindowSize!==-1)throw Error(`Local attention is not supported`);if(t.softcap!==0)throw Error(`Softcap is not supported`);if(t.rotaryInterleaved!==0)throw Error(`Rotary interleaved is not supported`);if(t.smoothSoftmax)throw Error(`Smooth softmax is not supported`);if(n.dims.length!==3&&n.dims.length!==5)throw Error(`Input query is expected to have 3 or 5 dimensions`);let s=n.dims[0],c=n.dims[1],l=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],u=c,d=0,f=!r||r.dims.length===0,p=Math.floor(f?l/(t.numHeads+2*t.kvNumHeads):l/t.numHeads);f&&(l=p*t.numHeads);let m=a&&a.dims.length!==0,h=o&&o.dims.length!==0;if(m&&a.dims.length===4&&a.dims[0]===s&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===p)throw Error(`BSNH pastKey/pastValue is not supported`);if(m&&h){if(a.dims.length!==4)throw Error(`Input "past_key" is expected to have 4 dimensions`);if(o.dims.length!==4)throw Error(`Input "past_value" is expected to have 4 dimensions`);d=a.dims[2]}else if(m||h)throw Error(`Input "past_key" and "past_value" shall be both present or both absent`);let g=1;if(r&&r.dims.length>0){if(n.dims.length!==3)throw Error(`Input "query" is expected to have 3 dimensions when key is given`);if(r.dims.length<3||r.dims.length>5)throw Error(`Input "key" is expected to have 3, 4, or 5 dimensions`);if(n.dims[0]!==r.dims[0])throw Error(`Input "query" and "key" shall have same dim 0 (batch size)`);if(r.dims.length===3){if(n.dims[2]%r.dims[2]!==0)throw Error(`Dimension 2 of "query" should be a multiple of "key"`);u=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==t.numHeads||r.dims[3]!==2||r.dims[4]!==p)throw Error(`Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv`);if(i)throw Error(`Expect "value" be none when "key" has packed kv format.`);u=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==p)throw Error(`Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key`);u=r.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw Error(`Input "query" is expected to have 3 or 5 dimensions when key is empty`);if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw Error(`Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv`);g=3}let _=!1,v=t.kvNumHeads?p*t.kvNumHeads:l;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw Error(`Input "value" is expected to have 3 or 4 dimensions`);if(n.dims[0]!==i.dims[0])throw Error(`Input "query" and "value" shall have same dim 0 (batch_size)`);if(i.dims.length===3){if(u!==i.dims[1])throw Error(`Input "key" and "value" shall have the same dim 1 (kv_sequence_length)`);v=i.dims[2]}else{if(u!==i.dims[2])throw Error(`Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)`);v=i.dims[1]*i.dims[3],_=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.dims[0]!==s)throw Error(`Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size`);return{batchSize:s,sequenceLength:c,pastSequenceLength:d,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:l,vHiddenSize:v,headSize:p,vHeadSize:Math.floor(v/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_,qkvFormat:g}},FX=LW({perm:[0,2,1,3]}),IX=(e,t,n)=>{let r=t,i=n.kvNumHeads;return t.dims.length===3&&n.kvSequenceLength!==0&&(r=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize]),r=e.compute(cG(r,FX.perm),{inputs:[r],outputs:[-1]})[0]),r},LX=(e,t,n,r)=>{let i=[`type`,`type`],a=[e*t],o=e*t,s=[{type:12,data:o},{type:12,data:t},{type:12,data:e}];return{name:`GeneratePositionIds`,shaderCache:{hint:`${e};${t}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:a,dataType:7}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:s}),getShaderSource:e=>{let t=$(`seq_lens`,n.dataType,n.dims),i=$(`total_seq_lens`,r.dataType,r.dims),o=XW(`pos_ids`,7,a);return`
14610
14610
  ${e.registerUniforms([{name:`output_size`,type:`u32`},{name:`sequence_length`,type:`u32`},{name:`batch_size`,type:`u32`}]).declareVariables(t,i,o)}
14611
14611
  ${e.mainStart()}
14612
14612
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -14637,7 +14637,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
14637
14637
  ${o.setByOffset(`global_idx`,`seqlen`)}
14638
14638
  };
14639
14639
  }
14640
- `}}},IX=(e,t)=>{let n=MX(e.inputs,t);if(e.inputs[0].dims.length===5)throw Error(`Packed QKV is not implemented`);if(e.inputs[1]?.dims.length===5)throw Error(`Packed KV is not implemented`);let r=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,s=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,c=e.inputs.length>4?e.inputs[5]:void 0,l=e.inputs.length>5?e.inputs[6]:void 0,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,d=FW({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,u*n.headSize,u*n.headSize]}),[f,p,m]=!i&&!a?e.compute(wX([r],d),{inputs:[r],outputs:[-1,-1,-1]}):[r,i,a],h,g;if(t.doRotary){let r=e.compute(FX(n.batchSize,n.sequenceLength,c,l),{inputs:[c,l],outputs:[-1]})[0],i=e.inputs[7],a=e.inputs[8],o=FW({interleaved:t.rotaryInterleaved!==0,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),s=[f,r,i,a],u=[-1];h=e.compute(kX(s,o),{inputs:s,outputs:u})[0],s.splice(0,1,p);let d=FW({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});g=e.compute(kX(s,d),{inputs:s,outputs:u})[0]}let _=_X(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?h:f,void 0,0),v=PX(e,t.doRotary?g:p,n),y=PX(e,m,n);hK(e,_,v,y,void 0,void 0,o,s,void 0,n,c,l)}}),RX,zX,BX,VX,HX=Z(()=>{VU(),iW(),lG(),$W(),RX=(e,t,n,r,i,a,o,s)=>{let c=HW(a),l=c===1?`f32`:`vec${c}f`,u=c===1?`vec2f`:`mat2x${c}f`,d=i*o,f=64;d===1&&(f=256);let p=[i,o,a/c],m=[i,o,2],h=[`rank`,`type`,`type`],g=[];return g.push(...VW(p,m)),e.compute({name:`InstanceNormComputeChannelScaleShift`,shaderCache:{hint:`${c};${s};${f}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:m,dataType:1}],dispatchGroup:{x:d},programUniforms:g}),getShaderSource:e=>{let i=$(`x`,t.dataType,3,c),a=[i,$(`scale`,n.dataType,n.dims),$(`bias`,r.dataType,r.dims),JW(`output`,1,3,2)];return`
14640
+ `}}},RX=(e,t)=>{let n=PX(e.inputs,t);if(e.inputs[0].dims.length===5)throw Error(`Packed QKV is not implemented`);if(e.inputs[1]?.dims.length===5)throw Error(`Packed KV is not implemented`);let r=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,s=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,c=e.inputs.length>4?e.inputs[5]:void 0,l=e.inputs.length>5?e.inputs[6]:void 0,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,d=LW({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,u*n.headSize,u*n.headSize]}),[f,p,m]=!i&&!a?e.compute(EX([r],d),{inputs:[r],outputs:[-1,-1,-1]}):[r,i,a],h,g;if(t.doRotary){let r=e.compute(LX(n.batchSize,n.sequenceLength,c,l),{inputs:[c,l],outputs:[-1]})[0],i=e.inputs[7],a=e.inputs[8],o=LW({interleaved:t.rotaryInterleaved!==0,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),s=[f,r,i,a],u=[-1];h=e.compute(jX(s,o),{inputs:s,outputs:u})[0],s.splice(0,1,p);let d=LW({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});g=e.compute(jX(s,d),{inputs:s,outputs:u})[0]}let _=yX(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?h:f,void 0,0),v=IX(e,t.doRotary?g:p,n),y=IX(e,m,n);_K(e,_,v,y,void 0,void 0,o,s,void 0,n,c,l)}}),BX,VX,HX,UX,WX=Z(()=>{UU(),oW(),dG(),tG(),BX=(e,t,n,r,i,a,o,s)=>{let c=WW(a),l=c===1?`f32`:`vec${c}f`,u=c===1?`vec2f`:`mat2x${c}f`,d=i*o,f=64;d===1&&(f=256);let p=[i,o,a/c],m=[i,o,2],h=[`rank`,`type`,`type`],g=[];return g.push(...UW(p,m)),e.compute({name:`InstanceNormComputeChannelScaleShift`,shaderCache:{hint:`${c};${s};${f}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:m,dataType:1}],dispatchGroup:{x:d},programUniforms:g}),getShaderSource:e=>{let i=$(`x`,t.dataType,3,c),a=[i,$(`scale`,n.dataType,n.dims),$(`bias`,r.dataType,r.dims),XW(`output`,1,3,2)];return`
14641
14641
  var<workgroup> workgroup_shared : array<${u}, ${f}>;
14642
14642
  const workgroup_size = ${f}u;
14643
14643
  ${e.declareVariables(...a)}
@@ -14663,15 +14663,15 @@ fn calculateOutputIndex(index: u32) -> u32 {
14663
14663
  workgroupBarrier();
14664
14664
  }
14665
14665
  if (local_idx == 0) {
14666
- let sum_final = ${GW(`workgroup_shared[0][0]`,c)} / f32(hight * ${c});
14667
- let squared_sum_final = ${GW(`workgroup_shared[0][1]`,c)} / f32(hight * ${c});
14666
+ let sum_final = ${qW(`workgroup_shared[0][0]`,c)} / f32(hight * ${c});
14667
+ let squared_sum_final = ${qW(`workgroup_shared[0][1]`,c)} / f32(hight * ${c});
14668
14668
 
14669
14669
  let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${s}));
14670
14670
  let channel_scale = inv_std_dev * f32(scale[channel]);
14671
14671
  let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
14672
14672
  output[workgroup_index] = vec2f(channel_scale, channel_shift);
14673
14673
  }
14674
- }`}},{inputs:[t,n,r],outputs:[-1]})[0]},zX=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],o=r[1],s=Q.sizeFromDimension(r,2),c=HW(s),l=Q.size(i)/c,u=RX(e,t[0],t[1],t[2],a,s,o,n.epsilon),d=[a,o,s/c],f=[a,o];e.compute({name:`InstanceNormalization`,shaderCache:{hint:`${c}`,inputDependencies:[`type`,`none`]},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...VW(d,f,d)]}),getShaderSource:e=>{let n=$(`x`,t[0].dataType,d.length,c),r=$(`scale_shift`,1,f.length,2),i=JW(`output`,t[0].dataType,d.length,c),a=[n,r,i];return`
14674
+ }`}},{inputs:[t,n,r],outputs:[-1]})[0]},VX=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],o=r[1],s=Q.sizeFromDimension(r,2),c=WW(s),l=Q.size(i)/c,u=BX(e,t[0],t[1],t[2],a,s,o,n.epsilon),d=[a,o,s/c],f=[a,o];e.compute({name:`InstanceNormalization`,shaderCache:{hint:`${c}`,inputDependencies:[`type`,`none`]},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...UW(d,f,d)]}),getShaderSource:e=>{let n=$(`x`,t[0].dataType,d.length,c),r=$(`scale_shift`,1,f.length,2),i=XW(`output`,t[0].dataType,d.length,c),a=[n,r,i];return`
14675
14675
  ${e.registerUniform(`output_size`,`u32`).declareVariables(...a)}
14676
14676
  ${e.mainStart()}
14677
14677
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -14681,7 +14681,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
14681
14681
  let scale_shift = ${r.getByIndices(`vec2<u32>(batch, channel)`)};
14682
14682
  let value = ${n.getByOffset(`global_idx`)} * ${i.type.value}(scale_shift.x) + ${i.type.value}(scale_shift.y);
14683
14683
  ${i.setByOffset(`global_idx`,`value`)};
14684
- }`}},{inputs:[t[0],u]})},BX=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],o=r[r.length-1],s=Q.sizeFromDimension(r,1)/o,c=HW(o),l=Q.size(i)/c,u=[{type:12,data:s},{type:12,data:Math.floor(o/c)}],d=[`type`,`type`],f=!1,p=[0,r.length-1];for(let e=0;e<r.length-2;e++)f||=r[e+1]!==1,p.push(e+1);f&&=r[r.length-1]!==1;let m=f?e.compute(oG(e.inputs[0],p),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:r.length},(e,t)=>r[p[t]])),h=RX(e,m,t[1],t[2],a,s,o,n.epsilon);e.compute({name:`InstanceNormalizationNHWC`,shaderCache:{hint:`${c}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:e=>{let n=zW(t[0].dataType),r=c===1?`vec2f`:`mat${c}x2f`,a=e=>{let t=e===0?`x`:`y`,r=c===1?`f32`:`vec${c}f`;switch(c){case 1:return`${n}(${r}(scale.${t}))`;case 2:return`vec2<${n}>(${r}(scale[0].${t}, scale[1].${t}))`;case 4:return`vec4<${n}>(${r}(scale[0].${t}, scale[1].${t}, scale[2].${t}, scale[3].${t}))`;default:throw Error(`Not supported compoents ${c}`)}},o=$(`input`,t[0].dataType,t[0].dims,c),s=JW(`output`,t[0].dataType,i,c);return`
14684
+ }`}},{inputs:[t[0],u]})},HX=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],o=r[r.length-1],s=Q.sizeFromDimension(r,1)/o,c=WW(o),l=Q.size(i)/c,u=[{type:12,data:s},{type:12,data:Math.floor(o/c)}],d=[`type`,`type`],f=!1,p=[0,r.length-1];for(let e=0;e<r.length-2;e++)f||=r[e+1]!==1,p.push(e+1);f&&=r[r.length-1]!==1;let m=f?e.compute(cG(e.inputs[0],p),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:r.length},(e,t)=>r[p[t]])),h=BX(e,m,t[1],t[2],a,s,o,n.epsilon);e.compute({name:`InstanceNormalizationNHWC`,shaderCache:{hint:`${c}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:e=>{let n=VW(t[0].dataType),r=c===1?`vec2f`:`mat${c}x2f`,a=e=>{let t=e===0?`x`:`y`,r=c===1?`f32`:`vec${c}f`;switch(c){case 1:return`${n}(${r}(scale.${t}))`;case 2:return`vec2<${n}>(${r}(scale[0].${t}, scale[1].${t}))`;case 4:return`vec4<${n}>(${r}(scale[0].${t}, scale[1].${t}, scale[2].${t}, scale[3].${t}))`;default:throw Error(`Not supported compoents ${c}`)}},o=$(`input`,t[0].dataType,t[0].dims,c),s=XW(`output`,t[0].dataType,i,c);return`
14685
14685
  @group(0) @binding(0) var<storage, read> input : array<${o.type.storage}>;
14686
14686
  @group(0) @binding(1) var<storage, read> scale_input : array<${r}>;
14687
14687
  @group(0) @binding(2) var<storage, read_write> output : array<${s.type.storage}>;
@@ -14695,35 +14695,35 @@ fn calculateOutputIndex(index: u32) -> u32 {
14695
14695
  let scale_offset = current_image_number * uniforms.C + current_channel_number;
14696
14696
  let scale = scale_input[scale_offset];
14697
14697
  output[global_idx] = fma(input[global_idx], ${a(0)}, ${a(1)});
14698
- }`}},{inputs:[t[0],h]})},VX=(e,t)=>{t.format===`NHWC`?BX(e,e.inputs,t):zX(e,e.inputs,t)}}),UX,WX,GX,KX=Z(()=>{VU(),iW(),$W(),UX=e=>{if(!e||e.length<2)throw Error(`layerNorm requires at least 2 inputs.`)},WX=(e,t,n)=>{let r=t.simplified,i=e[0].dims,a=e[1],o=!r&&e[2],s=i,c=Q.normalizeAxis(t.axis,i.length),l=Q.sizeToDimension(i,c),u=Q.sizeFromDimension(i,c),d=Q.size(a.dims),f=o?Q.size(o.dims):0;if(d!==u||o&&f!==u)throw Error(`Size of X.shape()[axis:] == ${u}.
14698
+ }`}},{inputs:[t[0],h]})},UX=(e,t)=>{t.format===`NHWC`?HX(e,e.inputs,t):VX(e,e.inputs,t)}}),GX,KX,qX,JX=Z(()=>{UU(),oW(),tG(),GX=e=>{if(!e||e.length<2)throw Error(`layerNorm requires at least 2 inputs.`)},KX=(e,t,n)=>{let r=t.simplified,i=e[0].dims,a=e[1],o=!r&&e[2],s=i,c=Q.normalizeAxis(t.axis,i.length),l=Q.sizeToDimension(i,c),u=Q.sizeFromDimension(i,c),d=Q.size(a.dims),f=o?Q.size(o.dims):0;if(d!==u||o&&f!==u)throw Error(`Size of X.shape()[axis:] == ${u}.
14699
14699
  Size of scale and bias (if provided) must match this.
14700
- Got scale size of ${d} and bias size of ${f}`);let p=[];for(let e=0;e<i.length;++e)e<c?p.push(i[e]):p.push(1);let m=HW(u),h=[`type`,`type`],g=[{type:12,data:l},{type:1,data:u},{type:12,data:Math.floor(u/m)},{type:1,data:t.epsilon}];o&&h.push(`type`);let _=n>1,v=n>2,y=t=>{let n=zW(e[0].dataType),i=[$(`x`,e[0].dataType,e[0].dims,m),$(`scale`,a.dataType,a.dims,m)];return o&&i.push($(`bias`,o.dataType,o.dims,m)),i.push(JW(`output`,e[0].dataType,s,m)),_&&i.push(JW(`mean_data_output`,1,p)),v&&i.push(JW(`inv_std_output`,1,p)),`
14700
+ Got scale size of ${d} and bias size of ${f}`);let p=[];for(let e=0;e<i.length;++e)e<c?p.push(i[e]):p.push(1);let m=WW(u),h=[`type`,`type`],g=[{type:12,data:l},{type:1,data:u},{type:12,data:Math.floor(u/m)},{type:1,data:t.epsilon}];o&&h.push(`type`);let _=n>1,v=n>2,y=t=>{let n=VW(e[0].dataType),i=[$(`x`,e[0].dataType,e[0].dims,m),$(`scale`,a.dataType,a.dims,m)];return o&&i.push($(`bias`,o.dataType,o.dims,m)),i.push(XW(`output`,e[0].dataType,s,m)),_&&i.push(XW(`mean_data_output`,1,p)),v&&i.push(XW(`inv_std_output`,1,p)),`
14701
14701
  ${t.registerUniforms([{name:`norm_count`,type:`u32`},{name:`norm_size`,type:`f32`},{name:`norm_size_vectorized`,type:`u32`},{name:`epsilon`,type:`f32`}]).declareVariables(...i)}
14702
14702
  ${t.mainStart()}
14703
14703
  ${t.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.norm_count`)}
14704
14704
  let offset = global_idx * uniforms.norm_size_vectorized;
14705
- var mean_vector = ${UW(`f32`,m)};
14706
- var mean_square_vector = ${UW(`f32`,m)};
14705
+ var mean_vector = ${GW(`f32`,m)};
14706
+ var mean_square_vector = ${GW(`f32`,m)};
14707
14707
 
14708
14708
  for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
14709
- let value = ${WW(n,m,`x[h + offset]`)};
14709
+ let value = ${KW(n,m,`x[h + offset]`)};
14710
14710
  mean_vector += value;
14711
14711
  mean_square_vector += value * value;
14712
14712
  }
14713
- let mean = ${GW(`mean_vector`,m)} / uniforms.norm_size;
14714
- let inv_std_dev = inverseSqrt(${GW(`mean_square_vector`,m)} / uniforms.norm_size ${r?``:`- mean * mean`} + uniforms.epsilon);
14713
+ let mean = ${qW(`mean_vector`,m)} / uniforms.norm_size;
14714
+ let inv_std_dev = inverseSqrt(${qW(`mean_square_vector`,m)} / uniforms.norm_size ${r?``:`- mean * mean`} + uniforms.epsilon);
14715
14715
 
14716
14716
  for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
14717
- let f32input = ${WW(n,m,`x[j + offset]`)};
14718
- let f32scale = ${WW(n,m,`scale[j]`)};
14717
+ let f32input = ${KW(n,m,`x[j + offset]`)};
14718
+ let f32scale = ${KW(n,m,`scale[j]`)};
14719
14719
  output[j + offset] = ${i[0].type.value}((f32input ${r?``:`- mean`}) * inv_std_dev * f32scale
14720
- ${o?`+ ${WW(n,m,`bias[j]`)}`:``}
14720
+ ${o?`+ ${KW(n,m,`bias[j]`)}`:``}
14721
14721
  );
14722
14722
  }
14723
14723
 
14724
14724
  ${_?`mean_data_output[global_idx] = mean`:``};
14725
14725
  ${v?`inv_std_output[global_idx] = inv_std_dev`:``};
14726
- }`},b=[{dims:s,dataType:e[0].dataType}];return _&&b.push({dims:p,dataType:1}),v&&b.push({dims:p,dataType:1}),{name:`LayerNormalization`,shaderCache:{hint:`${m};${n};${r}`,inputDependencies:h},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:g}),getShaderSource:y}},GX=(e,t)=>{UX(e.inputs),e.compute(WX(e.inputs,t,e.outputCount))}}),qX,JX,YX=Z(()=>{iW(),rJ(),fJ(),qX=e=>{if(!e||e.length!==2)throw Error(`MatMul requires 2 inputs.`);if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw Error(`shared dimension does not match.`)},JX=e=>{qX(e.inputs);let t=$U.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw Error(`Can't use matmul on the given tensors`);let n=t[t.length-1],r=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&r<8)e.compute(nJ(e.inputs,{activation:``},t));else{let i=t[t.length-2],a=Q.size(e.inputs[0].dims.slice(0,-2)),o=Q.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&i===1&&o===1){let i=e.inputs[0].reshape([1,a,r]),o=e.inputs[1].reshape([1,r,n]),s=[1,a,n],c=[i,o];e.compute(dJ(c,{activation:``},t,s),{inputs:c})}else e.compute(dJ(e.inputs,{activation:``},t))}}}),XX,ZX,QX,$X,eZ,tZ=Z(()=>{VU(),iW(),IW(),$W(),XX=(e,t)=>{if(e.length<3||e.length>4)throw Error(`MatMulNBits requires 3 or 4 inputs`);let n=e[0],r=n.dims.length;if(n.dims[r-1]!==t.k)throw Error(`The last dim of input shape does not match the k value`);let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,o=e[1];if(!Q.areEqual(o.dims,[t.n,i,a]))throw Error(`The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize`);let s=e[2].dims;if(Q.size(s)!==t.n*i)throw Error(`scales input size error.`);if(e.length===4){let n=e[3].dims,r=t.n*(t.bits===8?i:Math.floor((i*t.bits+7)/8));if(Q.size(n)!==r)throw Error(`zeroPoints input size error.`)}},ZX=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,o=t.n,s=n.slice(0,r-2),c=Q.size(s),l=e[1].dims[2]/4,u=e[0].dataType,d=HW(t.k),f=HW(l),p=HW(o),m=s.concat([i,o]),h=i>1&&o/p%2==0?2:1,g=Q.size(m)/p/h,_=[],v=[c,i,a/d],y=Q.convertShape(e[1].dims).slice();y.splice(-1,1,l/f),_.push(...VW(v)),_.push(...VW(y)),_.push(...VW(e[2].dims)),e.length===4&&_.push(...VW(Q.convertShape(e[3].dims)));let b=[c,i,o/p];return _.push(...VW(b)),{name:`MatMulNBits`,shaderCache:{hint:`${t.blockSize};${t.bits};${d};${f};${p};${h};64`,inputDependencies:Array(e.length).fill(`rank`)},getRunData:()=>({outputs:[{dims:m,dataType:u}],dispatchGroup:{x:g},programUniforms:_}),getShaderSource:n=>{let r=v.length,i=$(`a`,e[0].dataType,r,d),a=$(`b`,12,y.length,f),o=$(`scales`,e[2].dataType,e[2].dims.length),s=[i,a,o],c=e.length===4?$(`zero_points`,12,e[3].dims.length):void 0;c&&s.push(c);let u=b.length,m=JW(`output`,e[0].dataType,u,p),g=zW(e[0].dataType),_=(()=>{switch(d){case 1:return`array<${g}, 8>`;case 2:return`mat4x2<${g}>`;case 4:return`mat2x4<${g}>`;default:throw Error(`${d}-component is not supported.`)}})(),x=()=>{let e=`
14726
+ }`},b=[{dims:s,dataType:e[0].dataType}];return _&&b.push({dims:p,dataType:1}),v&&b.push({dims:p,dataType:1}),{name:`LayerNormalization`,shaderCache:{hint:`${m};${n};${r}`,inputDependencies:h},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:g}),getShaderSource:y}},qX=(e,t)=>{GX(e.inputs),e.compute(KX(e.inputs,t,e.outputCount))}}),YX,XX,ZX=Z(()=>{oW(),aJ(),mJ(),YX=e=>{if(!e||e.length!==2)throw Error(`MatMul requires 2 inputs.`);if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw Error(`shared dimension does not match.`)},XX=e=>{YX(e.inputs);let t=tW.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw Error(`Can't use matmul on the given tensors`);let n=t[t.length-1],r=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&r<8)e.compute(iJ(e.inputs,{activation:``},t));else{let i=t[t.length-2],a=Q.size(e.inputs[0].dims.slice(0,-2)),o=Q.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&i===1&&o===1){let i=e.inputs[0].reshape([1,a,r]),o=e.inputs[1].reshape([1,r,n]),s=[1,a,n],c=[i,o];e.compute(pJ(c,{activation:``},t,s),{inputs:c})}else e.compute(pJ(e.inputs,{activation:``},t))}}}),QX,$X,eZ,tZ,nZ,rZ=Z(()=>{UU(),oW(),RW(),tG(),QX=(e,t)=>{if(e.length<3||e.length>4)throw Error(`MatMulNBits requires 3 or 4 inputs`);let n=e[0],r=n.dims.length;if(n.dims[r-1]!==t.k)throw Error(`The last dim of input shape does not match the k value`);let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,o=e[1];if(!Q.areEqual(o.dims,[t.n,i,a]))throw Error(`The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize`);let s=e[2].dims;if(Q.size(s)!==t.n*i)throw Error(`scales input size error.`);if(e.length===4){let n=e[3].dims,r=t.n*(t.bits===8?i:Math.floor((i*t.bits+7)/8));if(Q.size(n)!==r)throw Error(`zeroPoints input size error.`)}},$X=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,o=t.n,s=n.slice(0,r-2),c=Q.size(s),l=e[1].dims[2]/4,u=e[0].dataType,d=WW(t.k),f=WW(l),p=WW(o),m=s.concat([i,o]),h=i>1&&o/p%2==0?2:1,g=Q.size(m)/p/h,_=[],v=[c,i,a/d],y=Q.convertShape(e[1].dims).slice();y.splice(-1,1,l/f),_.push(...UW(v)),_.push(...UW(y)),_.push(...UW(e[2].dims)),e.length===4&&_.push(...UW(Q.convertShape(e[3].dims)));let b=[c,i,o/p];return _.push(...UW(b)),{name:`MatMulNBits`,shaderCache:{hint:`${t.blockSize};${t.bits};${d};${f};${p};${h};64`,inputDependencies:Array(e.length).fill(`rank`)},getRunData:()=>({outputs:[{dims:m,dataType:u}],dispatchGroup:{x:g},programUniforms:_}),getShaderSource:n=>{let r=v.length,i=$(`a`,e[0].dataType,r,d),a=$(`b`,12,y.length,f),o=$(`scales`,e[2].dataType,e[2].dims.length),s=[i,a,o],c=e.length===4?$(`zero_points`,12,e[3].dims.length):void 0;c&&s.push(c);let u=b.length,m=XW(`output`,e[0].dataType,u,p),g=VW(e[0].dataType),_=(()=>{switch(d){case 1:return`array<${g}, 8>`;case 2:return`mat4x2<${g}>`;case 4:return`mat2x4<${g}>`;default:throw Error(`${d}-component is not supported.`)}})(),x=()=>{let e=`
14727
14727
  // reuse a data
14728
14728
  var input_offset = ${i.indicesToOffset(`${i.type.indices}(batch, row, word_offset)`)};
14729
14729
  var a_data: ${_};
@@ -14800,7 +14800,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
14800
14800
  }
14801
14801
  ${m.setByIndices(`${m.type.indices}(batch, row, col + local_id.x)`,`output_value`)};
14802
14802
  }
14803
- }`}}},QX=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,o=t.n,s=n.slice(0,r-2),c=Q.size(s),l=e[1].dims[2]/4,u=e[0].dataType,d=HW(t.k),f=HW(l),p=s.concat([i,o]),m=o%8==0?8:o%4==0?4:1,h=128/m,g=h*f*8,_=g/d,v=g/t.blockSize,y=Q.size(p)/m,b=[],x=[c,i,a/d],S=Q.convertShape(e[1].dims).slice();S.splice(-1,1,l/f),b.push(...VW(x)),b.push(...VW(S)),b.push(...VW(e[2].dims)),e.length===4&&b.push(...VW(Q.convertShape(e[3].dims)));let C=[c,i,o];return b.push(...VW(C)),{name:`BlockwiseMatMulNBits32`,shaderCache:{hint:`${t.blockSize};${d};${f};${h};${m}`,inputDependencies:Array(e.length).fill(`rank`)},getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:y},programUniforms:b}),getShaderSource:n=>{let r=x.length,i=$(`a`,e[0].dataType,r,d),a=$(`b`,12,S.length,f),o=$(`scales`,e[2].dataType,e[2].dims.length),s=[i,a,o],c=e.length===4?$(`zero_points`,12,e[3].dims.length):void 0;c&&s.push(c);let l=C.length,u=JW(`output`,e[0].dataType,l),p=zW(e[0].dataType),g=()=>{switch(d){case 1:return`
14803
+ }`}}},eZ=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,o=t.n,s=n.slice(0,r-2),c=Q.size(s),l=e[1].dims[2]/4,u=e[0].dataType,d=WW(t.k),f=WW(l),p=s.concat([i,o]),m=o%8==0?8:o%4==0?4:1,h=128/m,g=h*f*8,_=g/d,v=g/t.blockSize,y=Q.size(p)/m,b=[],x=[c,i,a/d],S=Q.convertShape(e[1].dims).slice();S.splice(-1,1,l/f),b.push(...UW(x)),b.push(...UW(S)),b.push(...UW(e[2].dims)),e.length===4&&b.push(...UW(Q.convertShape(e[3].dims)));let C=[c,i,o];return b.push(...UW(C)),{name:`BlockwiseMatMulNBits32`,shaderCache:{hint:`${t.blockSize};${d};${f};${h};${m}`,inputDependencies:Array(e.length).fill(`rank`)},getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:y},programUniforms:b}),getShaderSource:n=>{let r=x.length,i=$(`a`,e[0].dataType,r,d),a=$(`b`,12,S.length,f),o=$(`scales`,e[2].dataType,e[2].dims.length),s=[i,a,o],c=e.length===4?$(`zero_points`,12,e[3].dims.length):void 0;c&&s.push(c);let l=C.length,u=XW(`output`,e[0].dataType,l),p=VW(e[0].dataType),g=()=>{switch(d){case 1:return`
14804
14804
  let a_data0 = vec4<${p}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
14805
14805
  let a_data1 = vec4<${p}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`
14806
14806
  let a_data0 = vec4<${p}>(sub_a[word_offset], sub_a[word_offset + 1]);
@@ -14874,15 +14874,15 @@ fn calculateOutputIndex(index: u32) -> u32 {
14874
14874
  ${u.setByIndices(`${u.type.indices}(batch, row, col + local_idx)`,`output_value`)}
14875
14875
  }
14876
14876
  }
14877
- }`}}},$X=(e,t)=>{XX(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor(`intel`)&&e.adapterInfo.isArchitecture(`gen-12lp`)?e.compute(QX(e.inputs,t)):e.compute(ZX(e.inputs,t))},eZ=e=>FW(e)}),nZ,rZ,iZ,aZ,oZ,sZ,cZ,lZ,uZ,dZ=Z(()=>{VU(),iW(),$W(),nZ=e=>{if(!e||e.length<1)throw Error(`Too few inputs`);if(e[0].dataType!==1&&e[0].dataType!==10)throw Error(`Input type must be float or float16.`);if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw Error(`The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].`)}},rZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14878
- k = i32(${e.indicesGet(`indices`,i)}) - ${KW(`uniforms.pads`,i,n)};
14877
+ }`}}},tZ=(e,t)=>{QX(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor(`intel`)&&e.adapterInfo.isArchitecture(`gen-12lp`)?e.compute(eZ(e.inputs,t)):e.compute($X(e.inputs,t))},nZ=e=>LW(e)}),iZ,aZ,oZ,sZ,cZ,lZ,uZ,dZ,fZ,pZ=Z(()=>{UU(),oW(),tG(),iZ=e=>{if(!e||e.length<1)throw Error(`Too few inputs`);if(e[0].dataType!==1&&e[0].dataType!==10)throw Error(`Input type must be float or float16.`);if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw Error(`The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].`)}},aZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14878
+ k = i32(${e.indicesGet(`indices`,i)}) - ${JW(`uniforms.pads`,i,n)};
14879
14879
  if (k < 0) {
14880
14880
  break;
14881
14881
  }
14882
- if (k >= i32(${KW(`uniforms.x_shape`,i,t)})) {
14882
+ if (k >= i32(${JW(`uniforms.x_shape`,i,t)})) {
14883
14883
  break;
14884
14884
  }
14885
- offset += k * i32(${KW(`uniforms.x_strides`,i,t)});
14885
+ offset += k * i32(${JW(`uniforms.x_strides`,i,t)});
14886
14886
  `;return`
14887
14887
  value = ${e.type.value}(uniforms.constant_value);
14888
14888
  for (var i = 0; i < 1; i++) {
@@ -14891,53 +14891,53 @@ fn calculateOutputIndex(index: u32) -> u32 {
14891
14891
  ${r}
14892
14892
  value = x[offset];
14893
14893
  }
14894
- `},iZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14895
- k = i32(${e.indicesGet(`indices`,i)}) - ${KW(`uniforms.pads`,i,n)};
14894
+ `},oZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14895
+ k = i32(${e.indicesGet(`indices`,i)}) - ${JW(`uniforms.pads`,i,n)};
14896
14896
  if (k < 0) {
14897
14897
  k = -k;
14898
14898
  }
14899
14899
  {
14900
- let _2n_1 = 2 * (i32(${KW(`uniforms.x_shape`,i,t)}) - 1);
14900
+ let _2n_1 = 2 * (i32(${JW(`uniforms.x_shape`,i,t)}) - 1);
14901
14901
  k = k % _2n_1;
14902
- if(k >= i32(${KW(`uniforms.x_shape`,i,t)})) {
14902
+ if(k >= i32(${JW(`uniforms.x_shape`,i,t)})) {
14903
14903
  k = _2n_1 - k;
14904
14904
  }
14905
14905
  }
14906
- offset += k * i32(${KW(`uniforms.x_strides`,i,t)});
14906
+ offset += k * i32(${JW(`uniforms.x_strides`,i,t)});
14907
14907
  `;return`
14908
14908
  var offset = 0;
14909
14909
  var k = 0;
14910
14910
  ${r}
14911
14911
  value = x[offset];
14912
- `},aZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14913
- k = i32(${e.indicesGet(`indices`,i)}) - ${KW(`uniforms.pads`,i,n)};
14912
+ `},sZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14913
+ k = i32(${e.indicesGet(`indices`,i)}) - ${JW(`uniforms.pads`,i,n)};
14914
14914
  if (k < 0) {
14915
14915
  k = 0;
14916
14916
  }
14917
- if (k >= i32(${KW(`uniforms.x_shape`,i,t)})) {
14918
- k = i32(${KW(`uniforms.x_shape`,i,t)}) - 1;
14917
+ if (k >= i32(${JW(`uniforms.x_shape`,i,t)})) {
14918
+ k = i32(${JW(`uniforms.x_shape`,i,t)}) - 1;
14919
14919
  }
14920
- offset += k * i32(${KW(`uniforms.x_strides`,i,t)});
14920
+ offset += k * i32(${JW(`uniforms.x_strides`,i,t)});
14921
14921
  `;return`
14922
14922
  var offset = 0;
14923
14923
  var k = 0;
14924
14924
  ${r}
14925
14925
  value = x[offset];
14926
- `},oZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14927
- k = i32(${e.indicesGet(`indices`,i)}) - ${KW(`uniforms.pads`,i,n)};
14926
+ `},cZ=(e,t,n)=>{let r=``;for(let i=t-1;i>=0;--i)r+=`
14927
+ k = i32(${e.indicesGet(`indices`,i)}) - ${JW(`uniforms.pads`,i,n)};
14928
14928
  if (k < 0) {
14929
- k += i32(${KW(`uniforms.x_shape`,i,t)}]);
14929
+ k += i32(${JW(`uniforms.x_shape`,i,t)}]);
14930
14930
  }
14931
- if (k >= i32(${KW(`uniforms.x_shape`,i,t)})) {
14932
- k -= i32(${KW(`uniforms.x_shape`,i,t)});
14931
+ if (k >= i32(${JW(`uniforms.x_shape`,i,t)})) {
14932
+ k -= i32(${JW(`uniforms.x_shape`,i,t)});
14933
14933
  }
14934
- offset += k * i32(${KW(`uniforms.x_strides`,i,t)});
14934
+ offset += k * i32(${JW(`uniforms.x_strides`,i,t)});
14935
14935
  `;return`
14936
14936
  var offset = 0;
14937
14937
  var k = 0;
14938
14938
  ${r}
14939
14939
  value = x[offset];
14940
- `},sZ=(e,t,n)=>{switch(n.mode){case 0:return rZ(e,t,n.pads.length);case 1:return iZ(e,t,n.pads.length);case 2:return aZ(e,t,n.pads.length);case 3:return oZ(e,t,n.pads.length);default:throw Error(`Invalid mode`)}},cZ=(e,t)=>{let n=Q.padShape(e[0].dims.slice(),t.pads),r=e[0].dims,i=[{type:12,data:Q.size(n)},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;return t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...VW(e[0].dims,n)),{name:`Pad`,shaderCache:{hint:`${t.mode}${a}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Q.size(n)/64)},programUniforms:i}),getShaderSource:i=>{let o=JW(`output`,e[0].dataType,n.length),s=$(`x`,e[0].dataType,r.length),c=s.type.value,l=sZ(o,r.length,t),u=[{name:`output_size`,type:`u32`},{name:`pads`,type:`i32`,length:t.pads.length}];return t.mode===0&&u.push({name:`constant_value`,type:a?c:`f32`}),`
14940
+ `},lZ=(e,t,n)=>{switch(n.mode){case 0:return aZ(e,t,n.pads.length);case 1:return oZ(e,t,n.pads.length);case 2:return sZ(e,t,n.pads.length);case 3:return cZ(e,t,n.pads.length);default:throw Error(`Invalid mode`)}},uZ=(e,t)=>{let n=Q.padShape(e[0].dims.slice(),t.pads),r=e[0].dims,i=[{type:12,data:Q.size(n)},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;return t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...UW(e[0].dims,n)),{name:`Pad`,shaderCache:{hint:`${t.mode}${a}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Q.size(n)/64)},programUniforms:i}),getShaderSource:i=>{let o=XW(`output`,e[0].dataType,n.length),s=$(`x`,e[0].dataType,r.length),c=s.type.value,l=lZ(o,r.length,t),u=[{name:`output_size`,type:`u32`},{name:`pads`,type:`i32`,length:t.pads.length}];return t.mode===0&&u.push({name:`constant_value`,type:a?c:`f32`}),`
14941
14941
  ${i.registerUniforms(u).declareVariables(s,o)}
14942
14942
  ${i.mainStart()}
14943
14943
  ${i.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -14947,7 +14947,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
14947
14947
  var value = ${c}(0);
14948
14948
  ${l}
14949
14949
  output[global_idx] = value;
14950
- }`}}},lZ=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;e<t.length;e++)a[Number(t[e])]=Number(n[e]),a[Number(t[e])+i]=Number(n[e+t.length])}else n.forEach((e,t)=>a[Number(t)]=Number(e));let o=[];return a.forEach(e=>o.push(e)),{mode:t.mode,value:r,pads:o}}else return t},uZ=(e,t)=>{nZ(e.inputs);let n=lZ(e.inputs,t);e.compute(cZ(e.inputs,n),{inputs:[0]})}}),fZ,pZ,mZ,hZ,gZ,_Z,vZ,yZ,bZ,xZ,SZ,CZ,wZ,TZ,EZ,DZ,OZ,kZ,AZ,jZ=Z(()=>{LH(),VU(),iW(),$W(),fZ=e=>{if(QV.webgpu.validateInputContent&&(!e||e.length!==1))throw Error(`Pool ops requires 1 input.`)},pZ=(e,t,n)=>{let r=t.format===`NHWC`,i=e.dims.slice();r&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,`dilations`),o=t.kernelShape.slice(),s=t.strides.slice(),c=a?t.dilations.slice():[],l=t.pads.slice();eW.adjustPoolAttributes(n,i,o,s,c,l);let u=eW.computePoolOutputShape(n,i,s,c,o,l,t.autoPad),d=Object.assign({},t);a?Object.assign(d,{kernelShape:o,strides:s,pads:l,dilations:c,cacheKey:t.cacheKey}):Object.assign(d,{kernelShape:o,strides:s,pads:l,cacheKey:t.cacheKey});let f=u.slice();return f.push(f.splice(1,1)[0]),[d,r?f:u]},mZ=(e,t)=>{let n=t.format===`NHWC`,r=Q.size(e),i=Q.size(t.kernelShape),a=[{type:12,data:r},{type:12,data:i}],o=[{name:`outputSize`,type:`u32`},{name:`kernelSize`,type:`u32`}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],r=t.pads[t.pads.length/2-1],i=t.pads[t.pads.length-1],s=!!(r+i);a.push({type:12,data:e},{type:12,data:n},{type:12,data:r},{type:12,data:i}),o.push({name:`kw`,type:`u32`},{name:`sw`,type:`u32`},{name:`pwStart`,type:`u32`},{name:`pwEnd`,type:`u32`});let c=!1;if(t.kernelShape.length===2){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],r=t.pads[t.pads.length/2-2],i=t.pads[t.pads.length-2];c=!!(r+i),a.push({type:12,data:e},{type:12,data:n},{type:12,data:r},{type:12,data:i}),o.push({name:`kh`,type:`u32`},{name:`sh`,type:`u32`},{name:`phStart`,type:`u32`},{name:`phEnd`,type:`u32`})}return[a,o,!0,s,c]}else{if(n)throw Error(`Pooling with kernelShape.length > 2 is not supported for NHWC format.`);let e=Q.computeStrides(t.kernelShape);return a.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:`kernelStrides`,type:`u32`,length:e.length},{name:`pads`,type:`u32`,length:t.pads.length},{name:`strides`,type:`u32`,length:t.strides.length}),[a,o,!!t.pads.reduce((e,t)=>e+t),!1,!1]}},hZ=(e,t,n,r,i,a,o,s,c,l,u,d)=>{let f=i.format===`NHWC`,p=t.type.value,m=JW(`output`,t.type.tensor,r);if(i.kernelShape.length<=2){let r=``,l=``,h=``,g=n-(f?2:1);if(r=u?`
14950
+ }`}}},dZ=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;e<t.length;e++)a[Number(t[e])]=Number(n[e]),a[Number(t[e])+i]=Number(n[e+t.length])}else n.forEach((e,t)=>a[Number(t)]=Number(e));let o=[];return a.forEach(e=>o.push(e)),{mode:t.mode,value:r,pads:o}}else return t},fZ=(e,t)=>{iZ(e.inputs);let n=dZ(e.inputs,t);e.compute(uZ(e.inputs,n),{inputs:[0]})}}),mZ,hZ,gZ,_Z,vZ,yZ,bZ,xZ,SZ,CZ,wZ,TZ,EZ,DZ,OZ,kZ,AZ,jZ,MZ,NZ=Z(()=>{zH(),UU(),oW(),tG(),mZ=e=>{if(eH.webgpu.validateInputContent&&(!e||e.length!==1))throw Error(`Pool ops requires 1 input.`)},hZ=(e,t,n)=>{let r=t.format===`NHWC`,i=e.dims.slice();r&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,`dilations`),o=t.kernelShape.slice(),s=t.strides.slice(),c=a?t.dilations.slice():[],l=t.pads.slice();nW.adjustPoolAttributes(n,i,o,s,c,l);let u=nW.computePoolOutputShape(n,i,s,c,o,l,t.autoPad),d=Object.assign({},t);a?Object.assign(d,{kernelShape:o,strides:s,pads:l,dilations:c,cacheKey:t.cacheKey}):Object.assign(d,{kernelShape:o,strides:s,pads:l,cacheKey:t.cacheKey});let f=u.slice();return f.push(f.splice(1,1)[0]),[d,r?f:u]},gZ=(e,t)=>{let n=t.format===`NHWC`,r=Q.size(e),i=Q.size(t.kernelShape),a=[{type:12,data:r},{type:12,data:i}],o=[{name:`outputSize`,type:`u32`},{name:`kernelSize`,type:`u32`}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],r=t.pads[t.pads.length/2-1],i=t.pads[t.pads.length-1],s=!!(r+i);a.push({type:12,data:e},{type:12,data:n},{type:12,data:r},{type:12,data:i}),o.push({name:`kw`,type:`u32`},{name:`sw`,type:`u32`},{name:`pwStart`,type:`u32`},{name:`pwEnd`,type:`u32`});let c=!1;if(t.kernelShape.length===2){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],r=t.pads[t.pads.length/2-2],i=t.pads[t.pads.length-2];c=!!(r+i),a.push({type:12,data:e},{type:12,data:n},{type:12,data:r},{type:12,data:i}),o.push({name:`kh`,type:`u32`},{name:`sh`,type:`u32`},{name:`phStart`,type:`u32`},{name:`phEnd`,type:`u32`})}return[a,o,!0,s,c]}else{if(n)throw Error(`Pooling with kernelShape.length > 2 is not supported for NHWC format.`);let e=Q.computeStrides(t.kernelShape);return a.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:`kernelStrides`,type:`u32`,length:e.length},{name:`pads`,type:`u32`,length:t.pads.length},{name:`strides`,type:`u32`,length:t.strides.length}),[a,o,!!t.pads.reduce((e,t)=>e+t),!1,!1]}},_Z=(e,t,n,r,i,a,o,s,c,l,u,d)=>{let f=i.format===`NHWC`,p=t.type.value,m=XW(`output`,t.type.tensor,r);if(i.kernelShape.length<=2){let r=``,l=``,h=``,g=n-(f?2:1);if(r=u?`
14951
14951
  for (var i: u32 = 0u; i < uniforms.kw; i++) {
14952
14952
  xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;
14953
14953
  if (xIndices[${g}] < 0 || xIndices[${g}]
@@ -15022,23 +15022,23 @@ fn calculateOutputIndex(index: u32) -> u32 {
15022
15022
  for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
15023
15023
  var offset = i;
15024
15024
  for (var j = 0u; j < ${r-1}u; j++) {
15025
- offsets[j] = offset / ${KW(`uniforms.kernelStrides`,`j`,r)};
15026
- offset -= offsets[j] * ${KW(`uniforms.kernelStrides`,`j`,r)};
15025
+ offsets[j] = offset / ${JW(`uniforms.kernelStrides`,`j`,r)};
15026
+ offset -= offsets[j] * ${JW(`uniforms.kernelStrides`,`j`,r)};
15027
15027
  }
15028
15028
  offsets[${r-1}] = offset;
15029
15029
 
15030
15030
  isPad = false;
15031
15031
  for (var j = ${n-r}u; j < ${n}u; j++) {
15032
- xIndices[j] = indices[j] * ${KW(`uniforms.strides`,`j - ${n-r}u`,r)}
15033
- + offsets[j - ${n-r}u] - ${KW(`uniforms.pads`,`j - 2u`,u)};
15032
+ xIndices[j] = indices[j] * ${JW(`uniforms.strides`,`j - ${n-r}u`,r)}
15033
+ + offsets[j - ${n-r}u] - ${JW(`uniforms.pads`,`j - 2u`,u)};
15034
15034
  ${d}
15035
15035
  }
15036
15036
  ${o}
15037
15037
 
15038
15038
  output[global_idx] = value;
15039
- }`}},gZ=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,_Z=e=>`${gZ(e)};${e.countIncludePad}`,vZ=e=>`${gZ(e)};${e.storageOrder};${e.dilations}`,yZ=e=>({format:e.format,autoPad:[`NOTSET`,`VALID`,`SAME_UPPER`,`SAME_LOWER`][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),bZ=(e,t,n,r)=>{let[i,a]=pZ(t,r,n),o=$(`x`,t.dataType,t.dims.length),s=o.type.value,c=``;i.countIncludePad?c+=`value /= ${s}(uniforms.kernelSize);`:c+=`value /= ${s}(i32(uniforms.kernelSize) - pad);`;let[l,u,d,f,p]=mZ(a,i);return l.push(...VW(t.dims,a)),{name:e,shaderCache:{hint:`${r.cacheKey};${d};${f};${p}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Q.size(a)/64)},programUniforms:l}),getShaderSource:e=>hZ(e,o,t.dims.length,a.length,i,`value += x_val;`,c,0,u,d,f,p)}},xZ=e=>{let t=e.count_include_pad!==0,n=yZ(e);if(n.ceilMode!==0)throw Error(`using ceil() in shape computation is not yet supported for AveragePool`);let r={countIncludePad:t,...n,cacheKey:``};return{...r,cacheKey:_Z(r)}},SZ=(e,t)=>{fZ(e.inputs),e.compute(bZ(`AveragePool`,e.inputs[0],!1,t))},CZ={autoPad:``,ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},wZ=e=>{let t=e.format;return{format:t,...CZ,cacheKey:t}},TZ=(e,t)=>{fZ(e.inputs),e.compute(bZ(`GlobalAveragePool`,e.inputs[0],!0,t))},EZ=(e,t,n,r)=>{let[i,a]=pZ(t,r,n),o=$(`x`,t.dataType,t.dims.length),s=[`rank`],[c,l,u,d,f]=mZ(a,i);return c.push(...VW(t.dims,a)),{name:e,shaderCache:{hint:`${r.cacheKey};${u};${d};${f}`,inputDependencies:s},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Q.size(a)/64)},programUniforms:c}),getShaderSource:e=>hZ(e,o,t.dims.length,a.length,i,`
15039
+ }`}},vZ=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,yZ=e=>`${vZ(e)};${e.countIncludePad}`,bZ=e=>`${vZ(e)};${e.storageOrder};${e.dilations}`,xZ=e=>({format:e.format,autoPad:[`NOTSET`,`VALID`,`SAME_UPPER`,`SAME_LOWER`][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),SZ=(e,t,n,r)=>{let[i,a]=hZ(t,r,n),o=$(`x`,t.dataType,t.dims.length),s=o.type.value,c=``;i.countIncludePad?c+=`value /= ${s}(uniforms.kernelSize);`:c+=`value /= ${s}(i32(uniforms.kernelSize) - pad);`;let[l,u,d,f,p]=gZ(a,i);return l.push(...UW(t.dims,a)),{name:e,shaderCache:{hint:`${r.cacheKey};${d};${f};${p}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Q.size(a)/64)},programUniforms:l}),getShaderSource:e=>_Z(e,o,t.dims.length,a.length,i,`value += x_val;`,c,0,u,d,f,p)}},CZ=e=>{let t=e.count_include_pad!==0,n=xZ(e);if(n.ceilMode!==0)throw Error(`using ceil() in shape computation is not yet supported for AveragePool`);let r={countIncludePad:t,...n,cacheKey:``};return{...r,cacheKey:yZ(r)}},wZ=(e,t)=>{mZ(e.inputs),e.compute(SZ(`AveragePool`,e.inputs[0],!1,t))},TZ={autoPad:``,ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},EZ=e=>{let t=e.format;return{format:t,...TZ,cacheKey:t}},DZ=(e,t)=>{mZ(e.inputs),e.compute(SZ(`GlobalAveragePool`,e.inputs[0],!0,t))},OZ=(e,t,n,r)=>{let[i,a]=hZ(t,r,n),o=$(`x`,t.dataType,t.dims.length),s=[`rank`],[c,l,u,d,f]=gZ(a,i);return c.push(...UW(t.dims,a)),{name:e,shaderCache:{hint:`${r.cacheKey};${u};${d};${f}`,inputDependencies:s},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Q.size(a)/64)},programUniforms:c}),getShaderSource:e=>_Z(e,o,t.dims.length,a.length,i,`
15040
15040
  value = max(x_val, value);
15041
- `,``,t.dataType===10?-65504:-1e5,l,u,d,f)}},DZ=(e,t)=>{fZ(e.inputs),e.compute(EZ(`MaxPool`,e.inputs[0],!1,t))},OZ=e=>{let t=e.storage_order,n=e.dilations,r=yZ(e);if(t!==0)throw Error(`column major storage order is not yet supported for MaxPool`);if(r.ceilMode!==0)throw Error(`using ceil() in shape computation is not yet supported for MaxPool`);let i={storageOrder:t,dilations:n,...r,cacheKey:``};return{...i,cacheKey:vZ(i)}},kZ=e=>{let t=e.format;return{format:t,...CZ,cacheKey:t}},AZ=(e,t)=>{fZ(e.inputs),e.compute(EZ(`GlobalMaxPool`,e.inputs[0],!0,t))}}),MZ,NZ,PZ,FZ,IZ=Z(()=>{VU(),iW(),IW(),$W(),MZ=(e,t)=>{if(e.length<2||e.length>3)throw Error(`DequantizeLinear requires 2 or 3 inputs.`);if(e.length===3&&e[1].dims===e[2].dims)throw Error(`x-scale and x-zero-point must have the same shape.`);if(e.length===3&&e[0].dataType!==e[2].dataType)throw Error(`x and x-zero-point must have the same data type.`);if(e[0].dataType===6&&e.length>2)throw Error(`In the case of dequantizing int32 there is no zero point.`);if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw Error(`scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.`);if(e.length>2){if(e[0].dataType!==e[2].dataType)throw Error(`x and x-zero-point must have the same data type.`);if(e[1].dims.length!==e[2].dims.length)throw Error(`scale and zero-point inputs must have the same rank.`);if(!e[1].dims.map((t,n)=>t===e[2].dims[n]).reduce((e,t)=>e&&t,!0))throw Error(`scale and zero-point inputs must have the same shape.`)}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw Error(`blockSize must be set only for block quantization.`);if(!e[1].dims.map((n,r)=>r===t.axis||n===e[0].dims[r]).reduce((e,t)=>e&&t,!0))throw Error(`For block qunatization, scale input shape to match the input shape except for the axis`);if(e[1].dims.length!==e[0].dims.length)throw Error(`For block qunatization the scale input rank must be the same as the x rank.`);let n=e[0].dims[t.axis],r=e[1].dims[t.axis];if(t.blockSize<Math.ceil(n/r)||t.blockSize>Math.ceil(n/(r-1)-1))throw Error(`blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].`)}},NZ=(e,t)=>{let n=Q.normalizeAxis(t.axis,e[0].dims.length),r=e[0].dataType,i=r===3,a=e[0].dims,o=e[1].dataType,s=Q.size(a),c=r===3||r===2,l=c?[Math.ceil(Q.size(e[0].dims)/4)]:e[0].dims,u=e[1].dims,d=e.length>2?e[2]:void 0,f=d?c?[Math.ceil(Q.size(d.dims)/4)]:d.dims:void 0,p=u.length===0||u.length===1&&u[0]===1,m=p===!1&&u.length===1,h=HW(s),g=p&&(!c||h===4),_=g?h:1,v=g&&!c?h:1,y=$(`input`,c?12:r,l.length,v),b=$(`scale`,o,u.length),x=d?$(`zero_point`,c?12:r,f.length):void 0,S=JW(`output`,o,a.length,_),C=[y,b];x&&C.push(x);let w=[l,u];d&&w.push(f);let T=[{type:12,data:s/_},{type:12,data:n},{type:12,data:t.blockSize},...VW(...w,a)];return{name:`DequantizeLinear`,shaderCache:{hint:t.cacheKey,inputDependencies:x?[`rank`,`rank`,`rank`]:[`rank`,`rank`]},getShaderSource:e=>`
15041
+ `,``,t.dataType===10?-65504:-1e5,l,u,d,f)}},kZ=(e,t)=>{mZ(e.inputs),e.compute(OZ(`MaxPool`,e.inputs[0],!1,t))},AZ=e=>{let t=e.storage_order,n=e.dilations,r=xZ(e);if(t!==0)throw Error(`column major storage order is not yet supported for MaxPool`);if(r.ceilMode!==0)throw Error(`using ceil() in shape computation is not yet supported for MaxPool`);let i={storageOrder:t,dilations:n,...r,cacheKey:``};return{...i,cacheKey:bZ(i)}},jZ=e=>{let t=e.format;return{format:t,...TZ,cacheKey:t}},MZ=(e,t)=>{mZ(e.inputs),e.compute(OZ(`GlobalMaxPool`,e.inputs[0],!0,t))}}),PZ,FZ,IZ,LZ,RZ=Z(()=>{UU(),oW(),RW(),tG(),PZ=(e,t)=>{if(e.length<2||e.length>3)throw Error(`DequantizeLinear requires 2 or 3 inputs.`);if(e.length===3&&e[1].dims===e[2].dims)throw Error(`x-scale and x-zero-point must have the same shape.`);if(e.length===3&&e[0].dataType!==e[2].dataType)throw Error(`x and x-zero-point must have the same data type.`);if(e[0].dataType===6&&e.length>2)throw Error(`In the case of dequantizing int32 there is no zero point.`);if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw Error(`scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.`);if(e.length>2){if(e[0].dataType!==e[2].dataType)throw Error(`x and x-zero-point must have the same data type.`);if(e[1].dims.length!==e[2].dims.length)throw Error(`scale and zero-point inputs must have the same rank.`);if(!e[1].dims.map((t,n)=>t===e[2].dims[n]).reduce((e,t)=>e&&t,!0))throw Error(`scale and zero-point inputs must have the same shape.`)}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw Error(`blockSize must be set only for block quantization.`);if(!e[1].dims.map((n,r)=>r===t.axis||n===e[0].dims[r]).reduce((e,t)=>e&&t,!0))throw Error(`For block qunatization, scale input shape to match the input shape except for the axis`);if(e[1].dims.length!==e[0].dims.length)throw Error(`For block qunatization the scale input rank must be the same as the x rank.`);let n=e[0].dims[t.axis],r=e[1].dims[t.axis];if(t.blockSize<Math.ceil(n/r)||t.blockSize>Math.ceil(n/(r-1)-1))throw Error(`blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].`)}},FZ=(e,t)=>{let n=Q.normalizeAxis(t.axis,e[0].dims.length),r=e[0].dataType,i=r===3,a=e[0].dims,o=e[1].dataType,s=Q.size(a),c=r===3||r===2,l=c?[Math.ceil(Q.size(e[0].dims)/4)]:e[0].dims,u=e[1].dims,d=e.length>2?e[2]:void 0,f=d?c?[Math.ceil(Q.size(d.dims)/4)]:d.dims:void 0,p=u.length===0||u.length===1&&u[0]===1,m=p===!1&&u.length===1,h=WW(s),g=p&&(!c||h===4),_=g?h:1,v=g&&!c?h:1,y=$(`input`,c?12:r,l.length,v),b=$(`scale`,o,u.length),x=d?$(`zero_point`,c?12:r,f.length):void 0,S=XW(`output`,o,a.length,_),C=[y,b];x&&C.push(x);let w=[l,u];d&&w.push(f);let T=[{type:12,data:s/_},{type:12,data:n},{type:12,data:t.blockSize},...UW(...w,a)];return{name:`DequantizeLinear`,shaderCache:{hint:t.cacheKey,inputDependencies:x?[`rank`,`rank`,`rank`]:[`rank`,`rank`]},getShaderSource:e=>`
15042
15042
  ${e.registerUniforms([{name:`output_size`,type:`u32`},{name:`axis`,type:`u32`},{name:`block_size`,type:`u32`}]).declareVariables(...C,S)}
15043
15043
  ${e.mainStart()}
15044
15044
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -15076,12 +15076,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
15076
15076
  let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${x.getByIndices(`scale_indices`)};`:`let zero_point_value = ${c?i?`i32`:`u32`:y.type.value}(0);`};
15077
15077
  // Compute and write output
15078
15078
  ${S.setByOffset(`global_idx`,`${S.type.value}(x_value - zero_point_value) * scale_value`)};
15079
- }`,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(s/_/64),y:1,z:1},programUniforms:T})}},PZ=(e,t)=>{MZ(e.inputs,t),e.compute(NZ(e.inputs,t))},FZ=e=>FW({axis:e.axis,blockSize:e.blockSize})}),LZ,RZ,zZ,BZ=Z(()=>{LH(),VU(),$W(),LZ=(e,t,n)=>{if(e===t||e<t&&n<0||e>t&&n>0)throw Error(`Range these inputs' contents are invalid.`)},RZ=(e,t,n,r)=>{let i=Math.abs(Math.ceil((t-e)/n)),a=[i],o=i,s=[{type:12,data:o},{type:r,data:e},{type:r,data:n},...VW(a)];return{name:`Range`,shaderCache:{hint:`${r}`},getShaderSource:e=>{let t=JW(`output`,r,a.length),n=t.type.value,i=[{name:`outputSize`,type:`u32`},{name:`start`,type:n},{name:`delta`,type:n}];return`
15079
+ }`,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(s/_/64),y:1,z:1},programUniforms:T})}},IZ=(e,t)=>{PZ(e.inputs,t),e.compute(FZ(e.inputs,t))},LZ=e=>LW({axis:e.axis,blockSize:e.blockSize})}),zZ,BZ,VZ,HZ=Z(()=>{zH(),UU(),tG(),zZ=(e,t,n)=>{if(e===t||e<t&&n<0||e>t&&n>0)throw Error(`Range these inputs' contents are invalid.`)},BZ=(e,t,n,r)=>{let i=Math.abs(Math.ceil((t-e)/n)),a=[i],o=i,s=[{type:12,data:o},{type:r,data:e},{type:r,data:n},...UW(a)];return{name:`Range`,shaderCache:{hint:`${r}`},getShaderSource:e=>{let t=XW(`output`,r,a.length),n=t.type.value,i=[{name:`outputSize`,type:`u32`},{name:`start`,type:n},{name:`delta`,type:n}];return`
15080
15080
  ${e.registerUniforms(i).declareVariables(t)}
15081
15081
  ${e.mainStart()}
15082
15082
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.outputSize`)}
15083
15083
  output[global_idx] = uniforms.start + ${n}(global_idx) * uniforms.delta;
15084
- }`},getRunData:()=>({outputs:[{dims:a,dataType:r}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:s})}},zZ=e=>{let t=0,n=0,r=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],r=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],r=e.inputs[2].getFloat32Array()[0]),QV.webgpu.validateInputContent&&LZ(t,n,r),e.compute(RZ(t,n,r,e.inputs[0].dataType),{inputs:[]})}}),VZ,HZ,UZ,WZ,GZ=Z(()=>{VU(),iW(),IW(),$W(),VZ=(e,t,n,r)=>{if(e!==`none`&&r!==`i32`&&r!==`u32`&&r!==`f32`)throw Error(`Input ${r} is not supported with reduction ${e}.`);let i=`{
15084
+ }`},getRunData:()=>({outputs:[{dims:a,dataType:r}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:s})}},VZ=e=>{let t=0,n=0,r=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],r=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],r=e.inputs[2].getFloat32Array()[0]),eH.webgpu.validateInputContent&&zZ(t,n,r),e.compute(BZ(t,n,r,e.inputs[0].dataType),{inputs:[]})}}),UZ,WZ,GZ,KZ,qZ=Z(()=>{UU(),oW(),RW(),tG(),UZ=(e,t,n,r)=>{if(e!==`none`&&r!==`i32`&&r!==`u32`&&r!==`f32`)throw Error(`Input ${r} is not supported with reduction ${e}.`);let i=`{
15085
15085
  var oldValue = 0;
15086
15086
  loop {
15087
15087
  let newValueF32 =`,a=`;
@@ -15094,7 +15094,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15094
15094
  }
15095
15095
  }`;switch(e){case`none`:return`${t}=${n};`;case`add`:return r===`i32`||r===`u32`?`atomicAdd(&${t}, bitcast<${r}>(${n}));`:`
15096
15096
  ${i}bitcast<${r}>(oldValue) + (${n})${a}`;case`max`:return r===`i32`||r===`u32`?`atomicMax(&${t}, bitcast<${r}>(${n}));`:`
15097
- ${i}max(bitcast<f32>(oldValue), (${n}))${a}`;case`min`:return r===`i32`||r===`u32`?`atomicMin(&${t}, bitcast<${r}>(${n}));`:`${i}min(bitcast<${r}>(oldValue), (${n}))${a}`;case`mul`:return`${i}(bitcast<${r}>(oldValue) * (${n}))${a}`;default:throw Error(`Reduction ${e} is not supported.`)}},HZ=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n,a=Math.ceil(Q.sizeToDimension(r,r.length-1)/1),o=r[r.length-1],s=Q.sizeFromDimension(n,o),c=[{type:12,data:a},{type:12,data:o},{type:12,data:s},...VW(e[1].dims,e[2].dims,i)];return{name:`ScatterND`,shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:n=>{let r=$(`indices`,e[1].dataType,e[1].dims.length),a=$(`updates`,e[2].dataType,e[2].dims.length,1),o=t.reduction!==`none`&&t.reduction!==``?YW(`output`,e[0].dataType,i.length):JW(`output`,e[0].dataType,i.length,1);return`
15097
+ ${i}max(bitcast<f32>(oldValue), (${n}))${a}`;case`min`:return r===`i32`||r===`u32`?`atomicMin(&${t}, bitcast<${r}>(${n}));`:`${i}min(bitcast<${r}>(oldValue), (${n}))${a}`;case`mul`:return`${i}(bitcast<${r}>(oldValue) * (${n}))${a}`;default:throw Error(`Reduction ${e} is not supported.`)}},WZ=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n,a=Math.ceil(Q.sizeToDimension(r,r.length-1)/1),o=r[r.length-1],s=Q.sizeFromDimension(n,o),c=[{type:12,data:a},{type:12,data:o},{type:12,data:s},...UW(e[1].dims,e[2].dims,i)];return{name:`ScatterND`,shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:[`rank`,`rank`]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:n=>{let r=$(`indices`,e[1].dataType,e[1].dims.length),a=$(`updates`,e[2].dataType,e[2].dims.length,1),o=t.reduction!==`none`&&t.reduction!==``?ZW(`output`,e[0].dataType,i.length):XW(`output`,e[0].dataType,i.length,1);return`
15098
15098
  ${n.registerUniform(`output_size`,`u32`).registerUniform(`last_index_dimension`,`u32`).registerUniform(`num_updates_elements`,`u32`).declareVariables(r,a,o)}
15099
15099
  ${n.mainStart()}
15100
15100
  ${n.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.output_size`)}
@@ -15124,11 +15124,11 @@ fn calculateOutputIndex(index: u32) -> u32 {
15124
15124
 
15125
15125
  for (var i = 0u; i < uniforms.num_updates_elements; i++) {
15126
15126
  let value = updates[uniforms.num_updates_elements * global_idx + i];
15127
- ${VZ(t.reduction,`output[data_offset + i]`,`value`,o.type.value)}
15127
+ ${UZ(t.reduction,`output[data_offset + i]`,`value`,o.type.value)}
15128
15128
  }
15129
15129
 
15130
- }`}}},UZ=e=>FW({reduction:e.reduction}),WZ=(e,t)=>{e.compute(HZ(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),KZ,qZ,JZ,YZ,XZ,ZZ,QZ,$Z,eQ,tQ,nQ,rQ,iQ,aQ,oQ,sQ,cQ,lQ,uQ,dQ,fQ=Z(()=>{VU(),iW(),IW(),$W(),KZ=(e,t)=>{if(e.every(e=>e>0||(()=>{throw Error(`Resize requires scales input values to be positive`)})),e.length>0){if(t.mode===`linear`){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
15131
- one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode===`cubic`&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw Error(`Resize requires scales input size to be 2 or 4 for cubic mode`)}},qZ=(e,t,n)=>{t.every(e=>e>=0&&e<n||(()=>{throw Error(`Resize requires axes input values to be positive and less than rank`)}));let r=Array(n).fill(1);return t.forEach((t,n)=>r[t]=e[n]),r},JZ=(e,t,n,r,i,a)=>{let[o,s,c]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],l=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(e=>a.push(e));else if(t.coordinateTransformMode===`tf_crop_and_resize`)throw Error(`Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize`);if(s>0&&e.length>s&&e[s].dims.length===1&&e[s].dims[0]>0){if(e[s].getFloat32Array().forEach(e=>r.push(e)),r.length!==0&&r.length!==l&&n>=18&&r.length!==t.axes.length)throw Error(`Resize requires scales input size to be same as input rank or axes size for opset 18 and up`);KZ(r,t),t.axes.length>0&&qZ(r,t.axes,l).forEach((e,t)=>r[t]=e)}if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0&&(e[c].getBigInt64Array().forEach(e=>i.push(Number(e))),i.length!==0&&i.length!==l&&n>=18&&i.length!==t.axes.length))throw Error(`Resize requires sizes input size to be same as input rank or axes size for opset 18 and up`);if(t.axes.length>0){if(r.length!==0&&r.length!==t.axes.length)throw Error(`Resize requires "scales" input size to be of axes rank when axes attributes is specified`);if(i.length!==0&&i.length!==t.axes.length)throw Error(`Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified`)}if(typeof r<`u`&&typeof i<`u`&&r.length>0&&i.length>l)throw Error(`Resize requires only of scales or sizes to be specified`)},YZ=(e,t,n,r)=>`
15130
+ }`}}},GZ=e=>LW({reduction:e.reduction}),KZ=(e,t)=>{e.compute(WZ(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),JZ,YZ,XZ,ZZ,QZ,$Z,eQ,tQ,nQ,rQ,iQ,aQ,oQ,sQ,cQ,lQ,uQ,dQ,fQ,pQ,mQ=Z(()=>{UU(),oW(),RW(),tG(),JZ=(e,t)=>{if(e.every(e=>e>0||(()=>{throw Error(`Resize requires scales input values to be positive`)})),e.length>0){if(t.mode===`linear`){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
15131
+ one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode===`cubic`&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw Error(`Resize requires scales input size to be 2 or 4 for cubic mode`)}},YZ=(e,t,n)=>{t.every(e=>e>=0&&e<n||(()=>{throw Error(`Resize requires axes input values to be positive and less than rank`)}));let r=Array(n).fill(1);return t.forEach((t,n)=>r[t]=e[n]),r},XZ=(e,t,n,r,i,a)=>{let[o,s,c]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],l=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(e=>a.push(e));else if(t.coordinateTransformMode===`tf_crop_and_resize`)throw Error(`Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize`);if(s>0&&e.length>s&&e[s].dims.length===1&&e[s].dims[0]>0){if(e[s].getFloat32Array().forEach(e=>r.push(e)),r.length!==0&&r.length!==l&&n>=18&&r.length!==t.axes.length)throw Error(`Resize requires scales input size to be same as input rank or axes size for opset 18 and up`);JZ(r,t),t.axes.length>0&&YZ(r,t.axes,l).forEach((e,t)=>r[t]=e)}if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0&&(e[c].getBigInt64Array().forEach(e=>i.push(Number(e))),i.length!==0&&i.length!==l&&n>=18&&i.length!==t.axes.length))throw Error(`Resize requires sizes input size to be same as input rank or axes size for opset 18 and up`);if(t.axes.length>0){if(r.length!==0&&r.length!==t.axes.length)throw Error(`Resize requires "scales" input size to be of axes rank when axes attributes is specified`);if(i.length!==0&&i.length!==t.axes.length)throw Error(`Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified`)}if(typeof r<`u`&&typeof i<`u`&&r.length>0&&i.length>l)throw Error(`Resize requires only of scales or sizes to be specified`)},ZZ=(e,t,n,r)=>`
15132
15132
  // The whole part and the fractional part are calculated separately due to inaccuracy of floating
15133
15133
  // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
15134
15134
  // offset-by-one error later in floor().
@@ -15136,12 +15136,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
15136
15136
  let whole = ${r}(big / (${n}));
15137
15137
  let fract = ${r}(big % (${n})) / ${r}(${n});
15138
15138
  return whole + fract;
15139
- `,XZ=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
15139
+ `,QZ=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
15140
15140
  lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case`asymmetric`:return`
15141
15141
  if (xScale < 1.0 || floor(xScale) != xScale) {
15142
15142
  return ${t}(xResized) / ${t}(xScale);
15143
15143
  } else {
15144
- ${YZ(`xResized`,`lengthOriginal`,`lengthResized`,t)}
15144
+ ${ZZ(`xResized`,`lengthOriginal`,`lengthResized`,t)}
15145
15145
  }
15146
15146
  `;case`pytorch_half_pixel`:return`if (lengthResized > 1) {
15147
15147
  return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;
@@ -15150,7 +15150,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15150
15150
  }`;case`tf_half_pixel_for_nn`:return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case`align_corners`:return`if (lengthResized == 1) {
15151
15151
  return 0.0;
15152
15152
  } else {
15153
- ${YZ(`xResized`,`lengthOriginal - 1`,`lengthResized - 1`,t)}
15153
+ ${ZZ(`xResized`,`lengthOriginal - 1`,`lengthResized - 1`,t)}
15154
15154
  }`;case`tf_crop_and_resize`:return`if (lengthResized > 1) {
15155
15155
  return ${t}(roiStart) * ${t}(lengthOriginal - 1) +
15156
15156
  (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /
@@ -15161,38 +15161,38 @@ fn calculateOutputIndex(index: u32) -> u32 {
15161
15161
  const adjustment = ${t}(lengthResized) / outputWidth;
15162
15162
  const center = ${t}(lengthOriginal) / 2;
15163
15163
  const offset = center * (1 - adjustment);
15164
- return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case`half_pixel`:return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw Error(`Coordinate transform mode ${e} is not supported`)}})()+`}`,ZZ=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case`round_prefer_ceil`:return`if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }`;case`floor`:return`return floor(xOriginal);`;case`ceil`:return`return ceil(xOriginal);`;case`round_prefer_floor`:return`if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }`;default:if(t<11)return`if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }`;throw Error(`Nearest mode ${e} is not supported`)}})()+`}`,QZ=(e,t,n)=>{let r=Array(n).fill(0).concat(Array(n).fill(1)),i=e.length===0?r:e.slice();return t.length>0?(t.forEach((e,a)=>{r[e]=i[a],r[a+n]=i[t.length+a]}),r):i},$Z=(e,t,n,r)=>{let i=[];if(n.length>0)if(r.length>0){if(e.forEach(e=>i.push(e)),Math.max(...r)>e.length)throw Error(`axes is out of bound`);r.forEach((e,t)=>i[e]=n[t])}else n.forEach(e=>i.push(e));else{if(t.length===0)throw Error(`Resize requires either scales or sizes.`);i=e.map((e,n)=>Math.round(e*t[n]))}return i},eQ=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case`not_larger`:return n.axes.length>0?Math.min(...n.axes.map(e=>t[e]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case`not_smaller`:return n.axes.length>0?Math.max(...n.axes.map(e=>t[e]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return n.axes.length>0?(n.axes.forEach(e=>t[e]=r),n.axes.forEach(n=>i[n]=Math.round(e[n]*t[n]))):(t.fill(r,0,t.length),i.forEach((e,n)=>i[n]=Math.round(e*t[n]))),i},tQ=(e,t,n,r,i)=>`
15164
+ return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case`half_pixel`:return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw Error(`Coordinate transform mode ${e} is not supported`)}})()+`}`,$Z=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case`round_prefer_ceil`:return`if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }`;case`floor`:return`return floor(xOriginal);`;case`ceil`:return`return ceil(xOriginal);`;case`round_prefer_floor`:return`if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }`;default:if(t<11)return`if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }`;throw Error(`Nearest mode ${e} is not supported`)}})()+`}`,eQ=(e,t,n)=>{let r=Array(n).fill(0).concat(Array(n).fill(1)),i=e.length===0?r:e.slice();return t.length>0?(t.forEach((e,a)=>{r[e]=i[a],r[a+n]=i[t.length+a]}),r):i},tQ=(e,t,n,r)=>{let i=[];if(n.length>0)if(r.length>0){if(e.forEach(e=>i.push(e)),Math.max(...r)>e.length)throw Error(`axes is out of bound`);r.forEach((e,t)=>i[e]=n[t])}else n.forEach(e=>i.push(e));else{if(t.length===0)throw Error(`Resize requires either scales or sizes.`);i=e.map((e,n)=>Math.round(e*t[n]))}return i},nQ=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case`not_larger`:return n.axes.length>0?Math.min(...n.axes.map(e=>t[e]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case`not_smaller`:return n.axes.length>0?Math.max(...n.axes.map(e=>t[e]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return n.axes.length>0?(n.axes.forEach(e=>t[e]=r),n.axes.forEach(n=>i[n]=Math.round(e[n]*t[n]))):(t.fill(r,0,t.length),i.forEach((e,n)=>i[n]=Math.round(e*t[n]))),i},rQ=(e,t,n,r,i)=>`
15165
15165
  fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {
15166
15166
  var original_indices: array<${e.type.value}, ${n.length}>;
15167
15167
  for (var i:u32 = 0; i < ${n.length}; i++) {
15168
15168
  var output_index = ${e.indicesGet(`output_indices`,`i`)};
15169
- var scale = ${KW(`uniforms.scales`,`i`,r)};
15170
- var roi_low = ${KW(`uniforms.roi`,`i`,i)};
15171
- var roi_hi = ${KW(`uniforms.roi`,`i + ${t.length}`,i)};
15169
+ var scale = ${JW(`uniforms.scales`,`i`,r)};
15170
+ var roi_low = ${JW(`uniforms.roi`,`i`,i)};
15171
+ var roi_hi = ${JW(`uniforms.roi`,`i + ${t.length}`,i)};
15172
15172
  if (scale == 1.0) {
15173
15173
  original_indices[i] = ${e.type.value}(output_index);
15174
15174
  } else {
15175
- var input_shape_i = ${KW(`uniforms.input_shape`,`i`,t.length)};
15176
- var output_shape_i = ${KW(`uniforms.output_shape`,`i`,n.length)};
15175
+ var input_shape_i = ${JW(`uniforms.input_shape`,`i`,t.length)};
15176
+ var output_shape_i = ${JW(`uniforms.output_shape`,`i`,n.length)};
15177
15177
  original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
15178
15178
  input_shape_i, roi_low, roi_hi);
15179
15179
  }
15180
15180
  }
15181
15181
  return original_indices;
15182
- }`,nQ=(e,t,n,r,i,a,o)=>`
15182
+ }`,iQ=(e,t,n,r,i,a,o)=>`
15183
15183
  fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
15184
15184
  var input_indices: ${e.type.indices};
15185
15185
  for (var i:u32 = 0; i < ${r.length}; i++) {
15186
15186
  var output_index = ${t.indicesGet(`output_indices`,`i`)};
15187
15187
  var input_index: u32;
15188
- var scale = ${KW(`uniforms.scales`,`i`,i)};
15188
+ var scale = ${JW(`uniforms.scales`,`i`,i)};
15189
15189
  if (scale == 1.0) {
15190
15190
  input_index = output_index;
15191
15191
  } else {
15192
- var roi_low = ${KW(`uniforms.roi`,`i`,a)};
15193
- var roi_hi = ${KW(`uniforms.roi`,`i + ${n.length}`,a)};
15194
- var input_shape_i = ${KW(`uniforms.input_shape`,`i`,n.length)};
15195
- var output_shape_i = ${KW(`uniforms.output_shape`,`i`,r.length)};
15192
+ var roi_low = ${JW(`uniforms.roi`,`i`,a)};
15193
+ var roi_hi = ${JW(`uniforms.roi`,`i + ${n.length}`,a)};
15194
+ var input_shape_i = ${JW(`uniforms.input_shape`,`i`,n.length)};
15195
+ var output_shape_i = ${JW(`uniforms.output_shape`,`i`,r.length)};
15196
15196
  var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
15197
15197
  input_shape_i, roi_low, roi_hi);
15198
15198
  if (!${o} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {
@@ -15210,24 +15210,24 @@ fn calculateOutputIndex(index: u32) -> u32 {
15210
15210
  ${e.indicesSet(`input_indices`,`i`,`input_index`)}
15211
15211
  }
15212
15212
  return input_indices;
15213
- }`,rQ=(e,t)=>`
15213
+ }`,aQ=(e,t)=>`
15214
15214
  fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {
15215
15215
  for (var i:u32 = 0; i < ${t.length}; i++) {
15216
15216
  var input_index = ${e.indicesGet(`input_indices`,`i`)};
15217
- if (input_index < 0 || input_index >= ${KW(`uniforms.input_shape`,`i`,t.length)}) {
15217
+ if (input_index < 0 || input_index >= ${JW(`uniforms.input_shape`,`i`,t.length)}) {
15218
15218
  return false;
15219
15219
  }
15220
15220
  }
15221
15221
  return true;
15222
- }`,iQ=(e,t,n,r)=>e.rank>r?`
15222
+ }`,oQ=(e,t,n,r)=>e.rank>r?`
15223
15223
  ${e.indicesSet(`input_indices`,t,`channel`)};
15224
15224
  ${e.indicesSet(`input_indices`,n,`batch`)};
15225
- `:``,aQ=(e,t,n,r,i)=>{let[a,o,s,c]=n.length===2?[-1,0,1,-1]:[0,2,3,1],l=e.type.value;return`
15225
+ `:``,sQ=(e,t,n,r,i)=>{let[a,o,s,c]=n.length===2?[-1,0,1,-1]:[0,2,3,1],l=e.type.value;return`
15226
15226
  fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${l} {
15227
15227
  var input_indices: ${e.type.indices};
15228
15228
  ${e.indicesSet(`input_indices`,o,`max(0, min(row, ${n[o]} - 1))`)};
15229
15229
  ${e.indicesSet(`input_indices`,s,`max(0, min(col, ${n[s]} - 1))`)};
15230
- ${iQ(e,c,a,2)}
15230
+ ${oQ(e,c,a,2)}
15231
15231
  return ${e.getByIndices(`input_indices`)};
15232
15232
  }
15233
15233
 
@@ -15263,7 +15263,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15263
15263
  dy2 = 0.5;
15264
15264
  }
15265
15265
  return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
15266
- }`},oQ=(e,t,n,r,i,a,o,s,c,l)=>{let[u,d]=n.length===2?[0,1]:[2,3],f=e.type.value,p=o=>{let d=o===u?`row`:`col`;return`
15266
+ }`},cQ=(e,t,n,r,i,a,o,s,c,l)=>{let[u,d]=n.length===2?[0,1]:[2,3],f=e.type.value,p=o=>{let d=o===u?`row`:`col`;return`
15267
15267
  fn ${d}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${f} {
15268
15268
  var output_index = ${t.indicesGet(`output_indices`,o)};
15269
15269
  var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[o]},
@@ -15311,13 +15311,13 @@ fn calculateOutputIndex(index: u32) -> u32 {
15311
15311
  var input_indices: ${e.type.indices} = output_indices;
15312
15312
  return colCubicInterpolation(input_indices, output_indices);
15313
15313
  }
15314
- `},sQ=(e,t,n,r,i)=>{let[a,o,s,c,l]=n.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return`
15314
+ `},lQ=(e,t,n,r,i)=>{let[a,o,s,c,l]=n.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return`
15315
15315
  fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${u} {
15316
15316
  var input_indices: ${e.type.indices};
15317
15317
  ${e.indicesSet(`input_indices`,o,`max(0, min(depth, ${n[o]} - 1))`)};
15318
15318
  ${e.indicesSet(`input_indices`,s,`max(0, min(height, ${n[s]} - 1))`)};
15319
15319
  ${e.indicesSet(`input_indices`,c,`max(0, min(width, ${n[c]} - 1))`)};
15320
- ${iQ(e,l,a,3)}
15320
+ ${oQ(e,l,a,3)}
15321
15321
  return ${e.getByIndices(`input_indices`)};
15322
15322
  }
15323
15323
 
@@ -15370,18 +15370,18 @@ fn calculateOutputIndex(index: u32) -> u32 {
15370
15370
  }
15371
15371
  return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
15372
15372
  x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
15373
- }`},cQ=(e,t,n,r,i,a)=>{let o=e.dims,s=QZ(a,t.axes,o.length),c=$Z(o,r,i,t.axes),l=r.slice();r.length===0&&(l=o.map((e,t)=>e===0?1:c[t]/e),t.keepAspectRatioPolicy!==`stretch`&&(c=eQ(o,l,t)));let u=JW(`output`,e.dataType,c.length),d=$(`input`,e.dataType,o.length),f=Q.size(c),p=o.length===c.length&&o.every((e,t)=>e===c[t]),m=t.coordinateTransformMode===`tf_crop_and_resize`,h=t.extrapolationValue,g=d.type.value;return{name:`Resize`,shaderCache:{hint:`${t.cacheKey}|${n}|${l.length>0?t.mode===`cubic`?l:l.length:``}|${i.length>0?i:``}|${s.length>0?s:``}|${p}|${t.mode===`nearest`?o.length:o}`,inputDependencies:[`rank`]},getShaderSource:e=>`
15373
+ }`},uQ=(e,t,n,r,i,a)=>{let o=e.dims,s=eQ(a,t.axes,o.length),c=tQ(o,r,i,t.axes),l=r.slice();r.length===0&&(l=o.map((e,t)=>e===0?1:c[t]/e),t.keepAspectRatioPolicy!==`stretch`&&(c=nQ(o,l,t)));let u=XW(`output`,e.dataType,c.length),d=$(`input`,e.dataType,o.length),f=Q.size(c),p=o.length===c.length&&o.every((e,t)=>e===c[t]),m=t.coordinateTransformMode===`tf_crop_and_resize`,h=t.extrapolationValue,g=d.type.value;return{name:`Resize`,shaderCache:{hint:`${t.cacheKey}|${n}|${l.length>0?t.mode===`cubic`?l:l.length:``}|${i.length>0?i:``}|${s.length>0?s:``}|${p}|${t.mode===`nearest`?o.length:o}`,inputDependencies:[`rank`]},getShaderSource:e=>`
15374
15374
  ${p?``:`
15375
- ${XZ(t.coordinateTransformMode,g)};
15375
+ ${QZ(t.coordinateTransformMode,g)};
15376
15376
  ${(()=>{switch(t.mode){case`nearest`:return`
15377
- ${rQ(d,o)};
15378
- ${ZZ(t.nearestMode,n,g)};
15379
- ${nQ(d,u,o,c,l.length,s.length,m)};
15377
+ ${aQ(d,o)};
15378
+ ${$Z(t.nearestMode,n,g)};
15379
+ ${iQ(d,u,o,c,l.length,s.length,m)};
15380
15380
  `;case`linear`:return`
15381
- ${tQ(u,o,c,l.length,s.length)};
15382
- ${(()=>{if(o.length===2||o.length===4)return`${aQ(d,u,o,m,h)}`;if(o.length===3||o.length===5)return`${sQ(d,u,o,m,h)}`;throw Error(`Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.`)})()};
15381
+ ${rQ(u,o,c,l.length,s.length)};
15382
+ ${(()=>{if(o.length===2||o.length===4)return`${sQ(d,u,o,m,h)}`;if(o.length===3||o.length===5)return`${lQ(d,u,o,m,h)}`;throw Error(`Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.`)})()};
15383
15383
  `;case`cubic`:return`
15384
- ${(()=>{if(o.length===2||o.length===4)return`${oQ(d,u,o,c,l,s,t.cubicCoeffA,m,t.extrapolationValue,t.excludeOutside)}`;throw Error(`Cubic mode only supports input dims 2 and 4 are supported in linear mode.`)})()};
15384
+ ${(()=>{if(o.length===2||o.length===4)return`${cQ(d,u,o,c,l,s,t.cubicCoeffA,m,t.extrapolationValue,t.excludeOutside)}`;throw Error(`Cubic mode only supports input dims 2 and 4 are supported in linear mode.`)})()};
15385
15385
  `;default:throw Error(`Invalid resize mode`)}})()};
15386
15386
  `}
15387
15387
  ${e.registerUniform(`output_size`,`u32`).registerUniform(`scales`,`f32`,l.length).registerUniform(`roi`,`f32`,s.length).declareVariables(d,u)}
@@ -15397,7 +15397,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15397
15397
  output[global_idx] = ${t.extrapolationValue};
15398
15398
  }`;case`linear`:return`output[global_idx] = ${o.length===2||o.length===4?`bilinearInterpolation`:`trilinearInterpolation`}(output_indices);`;case`cubic`:return`output[global_idx] = bicubicInterpolation(output_indices);`;default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};
15399
15399
  `}
15400
- }`,getRunData:()=>({outputs:[{dims:c,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},{type:1,data:l},{type:1,data:s},...VW(o,c)]})}},lQ=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},uQ=(e,t)=>{let n=[],r=[],i=[],a=lQ(e);if(t.antialias!==0)throw Error(`Only default value (0) for Antialias attribute is supported`);JZ(e.inputs,t,a,n,r,i),e.compute(cQ(e.inputs[0],t,a,n,r,i),{inputs:[0]})},dQ=e=>{let t=e.antialias,n=e.axes,r=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,o=e.extrapolationValue,s=e.keepAspectRatioPolicy,c=e.mode,l=e.nearestMode===``?`simple`:e.nearestMode;return FW({antialias:t,axes:n,coordinateTransformMode:r,cubicCoeffA:i,excludeOutside:a,extrapolationValue:o,keepAspectRatioPolicy:s,mode:c,nearestMode:l})}}),pQ,mQ,hQ,gQ=Z(()=>{VU(),iW(),$W(),pQ=e=>{if(!e||e.length<3)throw Error(`layerNorm requires at least 3 inputs.`);let t=e[0],n=e[1],r=e[2];if(t.dataType!==n.dataType||t.dataType!==r.dataType)throw Error(`All inputs must have the same data type`);if(t.dims.length!==3&&t.dims.length!==2)throw Error(`Input must be 2D or 3D`);if(n.dims.length!==3&&n.dims.length!==2)throw Error(`Skip must be 2D or 3D`);let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==i)throw Error(`Skip must have the same hidden size as input`);if(n.dims[n.dims.length-2]!==a)throw Error(`Skip must have the same sequence length as input`);if(r.dims.length!==1)throw Error(`Gamma must be 1D`);if(r.dims[r.dims.length-1]!==i)throw Error(`Gamma must have the same hidden size as input`);if(e.length>3){let t=e[3];if(t.dims.length!==1)throw Error(`Beta must be 1D`);if(t.dims[t.dims.length-1]!==i)throw Error(`Beta must have the same hidden size as input`)}if(e.length>4){let t=e[4];if(t.dims.length!==1)throw Error(`Bias must be 1D`);if(t.dims[t.dims.length-1]!==i)throw Error(`Bias must have the same hidden size as input`)}},mQ=(e,t,n,r)=>{let i=t.simplified,a=e[0].dims,o=Q.size(a),s=a,c=o,l=a.slice(-1)[0],u=r?a.slice(0,-1).concat(1):[],d=!i&&e.length>3,f=e.length>4,p=r&&n>1,m=r&&n>2,h=n>3,g=HW(l),_=[{type:12,data:c},{type:12,data:g},{type:12,data:l},{type:1,data:t.epsilon}],v=t=>{let n=[{name:`output_size`,type:`u32`},{name:`components`,type:`u32`},{name:`hidden_size`,type:`u32`},{name:`epsilon`,type:`f32`}],r=[$(`x`,e[0].dataType,e[0].dims,g),$(`skip`,e[1].dataType,e[1].dims,g),$(`gamma`,e[2].dataType,e[2].dims,g)];d&&r.push($(`beta`,e[3].dataType,e[3].dims,g)),f&&r.push($(`bias`,e[4].dataType,e[4].dims,g)),r.push(JW(`output`,e[0].dataType,s,g)),p&&r.push(JW(`mean_output`,1,u)),m&&r.push(JW(`inv_std_output`,1,u)),h&&r.push(JW(`input_skip_bias_sum`,e[0].dataType,s,g));let a=zW(e[0].dataType),o=zW(1,g);return`
15400
+ }`,getRunData:()=>({outputs:[{dims:c,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},{type:1,data:l},{type:1,data:s},...UW(o,c)]})}},dQ=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},fQ=(e,t)=>{let n=[],r=[],i=[],a=dQ(e);if(t.antialias!==0)throw Error(`Only default value (0) for Antialias attribute is supported`);XZ(e.inputs,t,a,n,r,i),e.compute(uQ(e.inputs[0],t,a,n,r,i),{inputs:[0]})},pQ=e=>{let t=e.antialias,n=e.axes,r=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,o=e.extrapolationValue,s=e.keepAspectRatioPolicy,c=e.mode,l=e.nearestMode===``?`simple`:e.nearestMode;return LW({antialias:t,axes:n,coordinateTransformMode:r,cubicCoeffA:i,excludeOutside:a,extrapolationValue:o,keepAspectRatioPolicy:s,mode:c,nearestMode:l})}}),hQ,gQ,_Q,vQ=Z(()=>{UU(),oW(),tG(),hQ=e=>{if(!e||e.length<3)throw Error(`layerNorm requires at least 3 inputs.`);let t=e[0],n=e[1],r=e[2];if(t.dataType!==n.dataType||t.dataType!==r.dataType)throw Error(`All inputs must have the same data type`);if(t.dims.length!==3&&t.dims.length!==2)throw Error(`Input must be 2D or 3D`);if(n.dims.length!==3&&n.dims.length!==2)throw Error(`Skip must be 2D or 3D`);let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==i)throw Error(`Skip must have the same hidden size as input`);if(n.dims[n.dims.length-2]!==a)throw Error(`Skip must have the same sequence length as input`);if(r.dims.length!==1)throw Error(`Gamma must be 1D`);if(r.dims[r.dims.length-1]!==i)throw Error(`Gamma must have the same hidden size as input`);if(e.length>3){let t=e[3];if(t.dims.length!==1)throw Error(`Beta must be 1D`);if(t.dims[t.dims.length-1]!==i)throw Error(`Beta must have the same hidden size as input`)}if(e.length>4){let t=e[4];if(t.dims.length!==1)throw Error(`Bias must be 1D`);if(t.dims[t.dims.length-1]!==i)throw Error(`Bias must have the same hidden size as input`)}},gQ=(e,t,n,r)=>{let i=t.simplified,a=e[0].dims,o=Q.size(a),s=a,c=o,l=a.slice(-1)[0],u=r?a.slice(0,-1).concat(1):[],d=!i&&e.length>3,f=e.length>4,p=r&&n>1,m=r&&n>2,h=n>3,g=WW(l),_=[{type:12,data:c},{type:12,data:g},{type:12,data:l},{type:1,data:t.epsilon}],v=t=>{let n=[{name:`output_size`,type:`u32`},{name:`components`,type:`u32`},{name:`hidden_size`,type:`u32`},{name:`epsilon`,type:`f32`}],r=[$(`x`,e[0].dataType,e[0].dims,g),$(`skip`,e[1].dataType,e[1].dims,g),$(`gamma`,e[2].dataType,e[2].dims,g)];d&&r.push($(`beta`,e[3].dataType,e[3].dims,g)),f&&r.push($(`bias`,e[4].dataType,e[4].dims,g)),r.push(XW(`output`,e[0].dataType,s,g)),p&&r.push(XW(`mean_output`,1,u)),m&&r.push(XW(`inv_std_output`,1,u)),h&&r.push(XW(`input_skip_bias_sum`,e[0].dataType,s,g));let a=VW(e[0].dataType),o=VW(1,g);return`
15401
15401
 
15402
15402
  ${t.registerUniforms(n).declareVariables(...r)}
15403
15403
  var<workgroup> sum_shared : array<${o}, 64>;
@@ -15421,7 +15421,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15421
15421
  let value = input_value + skip_value + bias_value;
15422
15422
  ${h?`input_skip_bias_sum[offset + i] = value;`:``}
15423
15423
  output[offset + i] = value;
15424
- let f32_value = ${WW(a,g,`value`)};
15424
+ let f32_value = ${KW(a,g,`value`)};
15425
15425
  sum_shared[ix] += f32_value;
15426
15426
  sum_squared_shared[ix] += f32_value * f32_value;
15427
15427
  }
@@ -15439,8 +15439,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
15439
15439
 
15440
15440
  let sum = sum_shared[0];
15441
15441
  let square_sum = sum_squared_shared[0];
15442
- let mean = ${GW(`sum`,g)} / f32(uniforms.hidden_size);
15443
- let inv_std_dev = inverseSqrt(${GW(`square_sum`,g)} / f32(uniforms.hidden_size) ${i?``:`- mean * mean`} + uniforms.epsilon);
15442
+ let mean = ${qW(`sum`,g)} / f32(uniforms.hidden_size);
15443
+ let inv_std_dev = inverseSqrt(${qW(`square_sum`,g)} / f32(uniforms.hidden_size) ${i?``:`- mean * mean`} + uniforms.epsilon);
15444
15444
  ${p?`mean_output[global_idx] = mean;`:``}
15445
15445
  ${m?`inv_std_output[global_idx] = inv_std_dev;`:``}
15446
15446
 
@@ -15449,14 +15449,14 @@ fn calculateOutputIndex(index: u32) -> u32 {
15449
15449
  ${a}(inv_std_dev) * gamma[offset1d + i]
15450
15450
  ${d?`+ beta[offset1d + i]`:``};
15451
15451
  }
15452
- }`},y=[{dims:s,dataType:e[0].dataType}];return n>1&&y.push({dims:u,dataType:1}),n>2&&y.push({dims:u,dataType:1}),n>3&&y.push({dims:a,dataType:e[0].dataType}),{name:`SkipLayerNormalization`,shaderCache:{hint:`${g};${p};${m};${h}`,inputDependencies:e.map((e,t)=>`type`)},getShaderSource:v,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(c/l)},programUniforms:_})}},hQ=(e,t)=>{pQ(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(mQ(e.inputs,t,e.outputCount,!1),{outputs:n})}}),_Q,vQ,yQ,bQ,xQ,SQ,CQ,wQ,TQ=Z(()=>{VU(),iW(),IW(),$W(),_Q=(e,t)=>{if(!e||e.length<1)throw Error(`too few inputs`);if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw Error(`axes, starts and ends must have the same length`)}else if(t.starts.length!==t.ends.length)throw Error(`starts and ends must have the same length`);e.slice(1).forEach((t,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw Error(`Input ${n} must be an array of int32 or int64`)})},vQ=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(e=>n.push(Number(e)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(e=>n.push(Number(e)));else throw Error(`Input ${t} must be an array of int32 or int64`);return n},yQ=(e,t)=>{if(e.length>1){let t=vQ(e,1),n=vQ(e,2),r=vQ(e,3);return r.length===0&&(r=[...Array(e[0].dims.length).keys()]),FW({starts:t,ends:n,axes:r})}else return t},bQ=(e,t,n,r,i)=>{let a=e;return e<0&&(a+=n[r[t]]),i[t]<0?Math.max(0,Math.min(a,n[r[t]]-1)):Math.max(0,Math.min(a,n[r[t]]))},xQ=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
15452
+ }`},y=[{dims:s,dataType:e[0].dataType}];return n>1&&y.push({dims:u,dataType:1}),n>2&&y.push({dims:u,dataType:1}),n>3&&y.push({dims:a,dataType:e[0].dataType}),{name:`SkipLayerNormalization`,shaderCache:{hint:`${g};${p};${m};${h}`,inputDependencies:e.map((e,t)=>`type`)},getShaderSource:v,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(c/l)},programUniforms:_})}},_Q=(e,t)=>{hQ(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(gQ(e.inputs,t,e.outputCount,!1),{outputs:n})}}),yQ,bQ,xQ,SQ,CQ,wQ,TQ,EQ,DQ=Z(()=>{UU(),oW(),RW(),tG(),yQ=(e,t)=>{if(!e||e.length<1)throw Error(`too few inputs`);if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw Error(`axes, starts and ends must have the same length`)}else if(t.starts.length!==t.ends.length)throw Error(`starts and ends must have the same length`);e.slice(1).forEach((t,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw Error(`Input ${n} must be an array of int32 or int64`)})},bQ=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(e=>n.push(Number(e)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(e=>n.push(Number(e)));else throw Error(`Input ${t} must be an array of int32 or int64`);return n},xQ=(e,t)=>{if(e.length>1){let t=bQ(e,1),n=bQ(e,2),r=bQ(e,3);return r.length===0&&(r=[...Array(e[0].dims.length).keys()]),LW({starts:t,ends:n,axes:r})}else return t},SQ=(e,t,n,r,i)=>{let a=e;return e<0&&(a+=n[r[t]]),i[t]<0?Math.max(0,Math.min(a,n[r[t]]-1)):Math.max(0,Math.min(a,n[r[t]]))},CQ=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
15453
15453
  var input_indices: ${e.type.indices};
15454
15454
  var carry = 0u;
15455
15455
  for (var i = ${n.length-1}; i >= 0; i--) {
15456
- let input_shape_i = ${KW(`uniforms.input_shape`,`i`,n.length)};
15457
- let steps_i = ${KW(`uniforms.steps`,`i`,n.length)};
15458
- let signs_i = ${KW(`uniforms.signs`,`i`,n.length)};
15459
- let starts_i = ${KW(`uniforms.starts`,`i`,n.length)};
15456
+ let input_shape_i = ${JW(`uniforms.input_shape`,`i`,n.length)};
15457
+ let steps_i = ${JW(`uniforms.steps`,`i`,n.length)};
15458
+ let signs_i = ${JW(`uniforms.signs`,`i`,n.length)};
15459
+ let starts_i = ${JW(`uniforms.starts`,`i`,n.length)};
15460
15460
  var output_index = ${t.indicesGet(`output_indices`,`i`)};
15461
15461
  var input_index = output_index * steps_i + starts_i + carry;
15462
15462
  carry = input_index / input_shape_i;
@@ -15467,15 +15467,15 @@ fn calculateOutputIndex(index: u32) -> u32 {
15467
15467
  ${e.indicesSet(`input_indices`,`i`,`input_index`)};
15468
15468
  }
15469
15469
  return input_indices;
15470
- }`,SQ=(e,t)=>{let n=e[0].dims,r=Q.size(n),i=t.axes.length>0?Q.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],a=vQ(e,4);a.forEach(e=>e!==0||(()=>{throw Error(`step cannot be 0`)})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((e,t)=>bQ(e,t,n,i,a)),s=t.ends.map((e,t)=>bQ(e,t,n,i,a));if(i.length!==o.length||i.length!==s.length)throw Error(`start, ends and axes should have the same number of elements`);if(i.length!==n.length)for(let e=0;e<n.length;++e)i.includes(e)||(o.splice(e,0,0),s.splice(e,0,n[e]),a.splice(e,0,1));let c=a.map(e=>Math.sign(e));a.forEach((e,t,n)=>{if(e<0){let r=(s[t]-o[t])/e,i=o[t];o[t]=i+r*a[t],s[t]=i,n[t]=-e}});let l=n.slice(0);i.forEach((e,t)=>{l[e]=Math.ceil((s[e]-o[e])/a[e])});let u={dims:l,dataType:e[0].dataType},d=JW(`output`,e[0].dataType,l.length),f=$(`input`,e[0].dataType,e[0].dims.length),p=Q.size(l),m=[{name:`outputSize`,type:`u32`},{name:`starts`,type:`u32`,length:o.length},{name:`signs`,type:`i32`,length:c.length},{name:`steps`,type:`u32`,length:a.length}],h=[{type:12,data:p},{type:12,data:o},{type:6,data:c},{type:12,data:a},...VW(e[0].dims,l)];return{name:`Slice`,shaderCache:{hint:`${c.length}_${o.length}_${a.length}`,inputDependencies:[`rank`]},getShaderSource:e=>`
15470
+ }`,wQ=(e,t)=>{let n=e[0].dims,r=Q.size(n),i=t.axes.length>0?Q.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],a=bQ(e,4);a.forEach(e=>e!==0||(()=>{throw Error(`step cannot be 0`)})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((e,t)=>SQ(e,t,n,i,a)),s=t.ends.map((e,t)=>SQ(e,t,n,i,a));if(i.length!==o.length||i.length!==s.length)throw Error(`start, ends and axes should have the same number of elements`);if(i.length!==n.length)for(let e=0;e<n.length;++e)i.includes(e)||(o.splice(e,0,0),s.splice(e,0,n[e]),a.splice(e,0,1));let c=a.map(e=>Math.sign(e));a.forEach((e,t,n)=>{if(e<0){let r=(s[t]-o[t])/e,i=o[t];o[t]=i+r*a[t],s[t]=i,n[t]=-e}});let l=n.slice(0);i.forEach((e,t)=>{l[e]=Math.ceil((s[e]-o[e])/a[e])});let u={dims:l,dataType:e[0].dataType},d=XW(`output`,e[0].dataType,l.length),f=$(`input`,e[0].dataType,e[0].dims.length),p=Q.size(l),m=[{name:`outputSize`,type:`u32`},{name:`starts`,type:`u32`,length:o.length},{name:`signs`,type:`i32`,length:c.length},{name:`steps`,type:`u32`,length:a.length}],h=[{type:12,data:p},{type:12,data:o},{type:6,data:c},{type:12,data:a},...UW(e[0].dims,l)];return{name:`Slice`,shaderCache:{hint:`${c.length}_${o.length}_${a.length}`,inputDependencies:[`rank`]},getShaderSource:e=>`
15471
15471
  ${e.registerUniforms(m).declareVariables(f,d)}
15472
- ${xQ(f,d,n)}
15472
+ ${CQ(f,d,n)}
15473
15473
  ${e.mainStart()}
15474
15474
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.outputSize`)}
15475
15475
  let output_indices = ${d.offsetToIndices(`global_idx`)};
15476
15476
  let input_indices = calculateInputIndices(output_indices);
15477
15477
  ${d.setByOffset(`global_idx`,f.getByIndices(`input_indices`))}
15478
- }`,getRunData:()=>({outputs:[u],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:h})}},CQ=(e,t)=>{_Q(e.inputs,t);let n=yQ(e.inputs,t);e.compute(SQ(e.inputs,n),{inputs:[0]})},wQ=e=>{let t=e.starts,n=e.ends,r=e.axes;return FW({starts:t,ends:n,axes:r})}}),EQ,DQ,OQ,kQ,AQ=Z(()=>{VU(),iW(),IW(),lG(),$W(),EQ=e=>{if(!e||e.length!==1)throw Error(`Softmax op requires 1 input.`)},DQ=(e,t)=>{let n=e.inputs[0],r=n.dims,i=Q.size(r),a=r.length,o=Q.normalizeAxis(t.axis,a),s=o<r.length-1,c,l=[];s?(l=Array.from({length:a},(e,t)=>t),l[o]=a-1,l[a-1]=o,c=e.compute(oG(n,l),{inputs:[n],outputs:[-1]})[0]):c=n;let u=c.dims,d=u[a-1],f=i/d,p=HW(d),m=d/p,h=64;f===1&&(h=256);let g=(e,t)=>t===4?`max(max(${e}.x, ${e}.y), max(${e}.z, ${e}.w))`:t===2?`max(${e}.x, ${e}.y)`:t===3?`max(max(${e}.x, ${e}.y), ${e}.z)`:e,_=$(`x`,c.dataType,c.dims,p),v=JW(`result`,c.dataType,c.dims,p),y=_.type.value,b=zW(c.dataType)===`f32`?`var threadMax = ${y}(-3.4028234663852886e+38f);`:`var threadMax = ${y}(-65504.0h);`,x=e.compute({name:`Softmax`,shaderCache:{hint:`${p};${h}`,inputDependencies:[`type`]},getRunData:()=>({outputs:[{dims:u,dataType:c.dataType}],dispatchGroup:{x:f},programUniforms:[{type:6,data:m}]}),getShaderSource:e=>`
15478
+ }`,getRunData:()=>({outputs:[u],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:h})}},TQ=(e,t)=>{yQ(e.inputs,t);let n=xQ(e.inputs,t);e.compute(wQ(e.inputs,n),{inputs:[0]})},EQ=e=>{let t=e.starts,n=e.ends,r=e.axes;return LW({starts:t,ends:n,axes:r})}}),OQ,kQ,AQ,jQ,MQ=Z(()=>{UU(),oW(),RW(),dG(),tG(),OQ=e=>{if(!e||e.length!==1)throw Error(`Softmax op requires 1 input.`)},kQ=(e,t)=>{let n=e.inputs[0],r=n.dims,i=Q.size(r),a=r.length,o=Q.normalizeAxis(t.axis,a),s=o<r.length-1,c,l=[];s?(l=Array.from({length:a},(e,t)=>t),l[o]=a-1,l[a-1]=o,c=e.compute(cG(n,l),{inputs:[n],outputs:[-1]})[0]):c=n;let u=c.dims,d=u[a-1],f=i/d,p=WW(d),m=d/p,h=64;f===1&&(h=256);let g=(e,t)=>t===4?`max(max(${e}.x, ${e}.y), max(${e}.z, ${e}.w))`:t===2?`max(${e}.x, ${e}.y)`:t===3?`max(max(${e}.x, ${e}.y), ${e}.z)`:e,_=$(`x`,c.dataType,c.dims,p),v=XW(`result`,c.dataType,c.dims,p),y=_.type.value,b=VW(c.dataType)===`f32`?`var threadMax = ${y}(-3.4028234663852886e+38f);`:`var threadMax = ${y}(-65504.0h);`,x=e.compute({name:`Softmax`,shaderCache:{hint:`${p};${h}`,inputDependencies:[`type`]},getRunData:()=>({outputs:[{dims:u,dataType:c.dataType}],dispatchGroup:{x:f},programUniforms:[{type:6,data:m}]}),getShaderSource:e=>`
15479
15479
  var<workgroup> rowMaxShared : ${y};
15480
15480
  var<workgroup> rowSumShared : ${y};
15481
15481
  var<workgroup> threadShared : array<${y}, ${h}>;
@@ -15538,7 +15538,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15538
15538
  workgroupBarrier();
15539
15539
  }
15540
15540
  if (lindex == 0) {
15541
- rowSumShared = ${y}(${GW(`threadShared[0]`,p)});
15541
+ rowSumShared = ${y}(${qW(`threadShared[0]`,p)});
15542
15542
  }
15543
15543
  workgroupBarrier();
15544
15544
 
@@ -15549,7 +15549,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15549
15549
  value = max(value, ${y}(0.0));
15550
15550
  setValue(row, col, row_stride, value);
15551
15551
  }
15552
- }`},{inputs:[c],outputs:[s?-1:0]})[0];s&&e.compute(oG(x,l),{inputs:[x]})},OQ=(e,t)=>{EQ(e.inputs),DQ(e,t)},kQ=e=>FW({axis:e.axis})}),jQ,MQ,NQ,PQ,FQ,IQ=Z(()=>{VU(),iW(),$W(),jQ=e=>Array.from(e.getBigInt64Array(),Number),MQ=e=>{if(!e||e.length!==2)throw Error(`Tile requires 2 inputs.`);if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw Error(`Tile only support float, float16, int32, and uint32 data types`);if(e[1].dataType!==7)throw Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw Error("Tile `repeats` input should be 1-D");if(jQ(e[1]).length!==e[0].dims.length)throw Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},NQ=(e,t)=>{let n=[];for(let r=0;r<e.length;++r)n.push(e[r]*t[r]);return n},PQ=(e,t)=>{let n=e[0].dims,r=t??jQ(e[1]),i=NQ(n,r),a=Q.size(i),o=e[0].dataType,s=$(`input`,o,n.length),c=JW(`output`,o,i.length);return{name:`Tile`,shaderCache:{hint:`${r}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...VW(e[0].dims,i)]}),getShaderSource:e=>`
15552
+ }`},{inputs:[c],outputs:[s?-1:0]})[0];s&&e.compute(cG(x,l),{inputs:[x]})},AQ=(e,t)=>{OQ(e.inputs),kQ(e,t)},jQ=e=>LW({axis:e.axis})}),NQ,PQ,FQ,IQ,LQ,RQ=Z(()=>{UU(),oW(),tG(),NQ=e=>Array.from(e.getBigInt64Array(),Number),PQ=e=>{if(!e||e.length!==2)throw Error(`Tile requires 2 inputs.`);if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw Error(`Tile only support float, float16, int32, and uint32 data types`);if(e[1].dataType!==7)throw Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw Error("Tile `repeats` input should be 1-D");if(NQ(e[1]).length!==e[0].dims.length)throw Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},FQ=(e,t)=>{let n=[];for(let r=0;r<e.length;++r)n.push(e[r]*t[r]);return n},IQ=(e,t)=>{let n=e[0].dims,r=t??NQ(e[1]),i=FQ(n,r),a=Q.size(i),o=e[0].dataType,s=$(`input`,o,n.length),c=XW(`output`,o,i.length);return{name:`Tile`,shaderCache:{hint:`${r}`,inputDependencies:[`rank`]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...UW(e[0].dims,i)]}),getShaderSource:e=>`
15553
15553
  const inputShape = ${s.indices(...n)};
15554
15554
  ${e.registerUniform(`output_size`,`u32`).declareVariables(s,c)}
15555
15555
  ${e.mainStart()}
@@ -15563,7 +15563,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15563
15563
  ${s.indicesSet(`input_indices`,`i`,`input_dim_value`)}
15564
15564
  }
15565
15565
  ${c.setByOffset(`global_idx`,s.getByIndices(`input_indices`))}
15566
- }`}},FQ=e=>{MQ(e.inputs),e.compute(PQ(e.inputs),{inputs:[0]})}}),LQ,RQ,zQ,BQ=Z(()=>{VU(),iW(),$W(),LQ=(e,t,n,r,i)=>{let a=JW(`output_data`,i,n.length,4),o=$(`a_data`,t[1].dataType,t[1].dims.length,4),s=$(`b_data`,t[2].dataType,t[2].dims.length,4),c=$(`c_data`,t[0].dataType,t[0].dims.length,4),l,u=(e,t,n)=>`select(${t}, ${e}, ${n})`;if(!r)l=a.setByOffset(`global_idx`,u(o.getByOffset(`global_idx`),s.getByOffset(`global_idx`),c.getByOffset(`global_idx`)));else{let e=(e,t,n=``)=>{let r=`a_data[index_a${t}][component_a${t}]`,i=`b_data[index_b${t}][component_b${t}]`,l=`bool(c_data[index_c${t}] & (0xffu << (component_c${t} * 8)))`;return`
15566
+ }`}},LQ=e=>{PQ(e.inputs),e.compute(IQ(e.inputs),{inputs:[0]})}}),zQ,BQ,VQ,HQ=Z(()=>{UU(),oW(),tG(),zQ=(e,t,n,r,i)=>{let a=XW(`output_data`,i,n.length,4),o=$(`a_data`,t[1].dataType,t[1].dims.length,4),s=$(`b_data`,t[2].dataType,t[2].dims.length,4),c=$(`c_data`,t[0].dataType,t[0].dims.length,4),l,u=(e,t,n)=>`select(${t}, ${e}, ${n})`;if(!r)l=a.setByOffset(`global_idx`,u(o.getByOffset(`global_idx`),s.getByOffset(`global_idx`),c.getByOffset(`global_idx`)));else{let e=(e,t,n=``)=>{let r=`a_data[index_a${t}][component_a${t}]`,i=`b_data[index_b${t}][component_b${t}]`,l=`bool(c_data[index_c${t}] & (0xffu << (component_c${t} * 8)))`;return`
15567
15567
  let output_indices${t} = ${a.offsetToIndices(`global_idx * 4u + ${t}u`)};
15568
15568
  let offset_a${t} = ${o.broadcastedIndicesToOffset(`output_indices${t}`,a)};
15569
15569
  let offset_b${t} = ${s.broadcastedIndicesToOffset(`output_indices${t}`,a)};
@@ -15591,7 +15591,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
15591
15591
  ${e.mainStart()}
15592
15592
  ${e.guardAgainstOutOfBoundsWorkgroupSizes(`uniforms.vec_size`)}
15593
15593
  ${l}
15594
- }`},RQ=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,i=e[1].dataType,a=!(Q.areEqual(t,n)&&Q.areEqual(n,r)),o=t,s=Q.size(t);if(a){let e=$U.calcShape($U.calcShape(t,n,!1),r,!1);if(!e)throw Error(`Can't perform where op on the given tensors`);o=e,s=Q.size(o)}let c=Math.ceil(s/4);return{name:`Where`,shaderCache:{inputDependencies:[`rank`,`rank`,`rank`]},getShaderSource:t=>LQ(t,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(s/64/4)},programUniforms:[{type:12,data:c},...VW(r,t,n,o)]})}},zQ=e=>{e.compute(RQ(e.inputs))}}),VQ,HQ=Z(()=>{lK(),vK(),CK(),DK(),Cq(),Lq(),Wq(),LJ(),YJ(),$J(),aY(),_Y(),CY(),EY(),jY(),FY(),BY(),GY(),XY(),dX(),LX(),HX(),KX(),YX(),tZ(),yX(),dZ(),jZ(),IZ(),BZ(),GZ(),iK(),fQ(),jX(),gQ(),TQ(),AQ(),DX(),IQ(),lG(),yq(),BQ(),VQ=new Map([[`Abs`,[AK]],[`Acos`,[jK]],[`Acosh`,[MK]],[`Add`,[Dq]],[`ArgMax`,[sK,cK]],[`ArgMin`,[oK,cK]],[`Asin`,[NK]],[`Asinh`,[PK]],[`Atan`,[FK]],[`Atanh`,[IK]],[`Attention`,[_K]],[`AveragePool`,[SZ,xZ]],[`BatchNormalization`,[SK]],[`BiasAdd`,[EK]],[`BiasSplitGelu`,[Sq]],[`Cast`,[RK,LK]],[`Ceil`,[VK]],[`Clip`,[BK]],[`Concat`,[Hq,Uq]],[`Conv`,[IJ,MJ]],[`ConvTranspose`,[JJ,WJ]],[`Cos`,[HK]],[`Cosh`,[UK]],[`CumSum`,[ZJ,QJ]],[`DepthToSpace`,[rY,iY]],[`DequantizeLinear`,[PZ,FZ]],[`Div`,[Oq]],[`Einsum`,[hY,gY]],[`Elu`,[GK,WK]],[`Equal`,[kq]],[`Erf`,[qK]],[`Exp`,[JK]],[`Expand`,[SY]],[`FastGelu`,[TY]],[`Floor`,[YK]],[`FusedConv`,[IJ,MJ]],[`Gather`,[AY,kY]],[`GatherElements`,[WY,UY]],[`GatherBlockQuantized`,[RY,zY]],[`GatherND`,[NY,PY]],[`Gelu`,[XK]],[`Gemm`,[YY,JY]],[`GlobalAveragePool`,[TZ,wZ]],[`GlobalMaxPool`,[AZ,kZ]],[`Greater`,[Nq]],[`GreaterOrEqual`,[Fq]],[`GridSample`,[lX,uX]],[`GroupQueryAttention`,[IX]],[`HardSigmoid`,[iq,rq]],[`InstanceNormalization`,[VX]],[`LayerNormalization`,[GX]],[`LeakyRelu`,[ZK,WK]],[`Less`,[Pq]],[`LessOrEqual`,[Iq]],[`Log`,[hq]],[`MatMul`,[JX]],[`MatMulNBits`,[$X,eZ]],[`MaxPool`,[DZ,OZ]],[`Mul`,[Aq]],[`MultiHeadAttention`,[vX,mX]],[`Neg`,[$K]],[`Not`,[QK]],[`Pad`,[uZ]],[`Pow`,[jq]],[`QuickGelu`,[vq,WK]],[`Range`,[zZ]],[`Reciprocal`,[eq]],[`ReduceMin`,[$G]],[`ReduceMean`,[JG]],[`ReduceMax`,[QG]],[`ReduceSum`,[tK]],[`ReduceProd`,[eK]],[`ReduceL1`,[YG]],[`ReduceL2`,[XG]],[`ReduceLogSum`,[rK]],[`ReduceLogSumExp`,[ZG]],[`ReduceSumSquare`,[nK]],[`Relu`,[tq]],[`Resize`,[uQ,dQ]],[`RotaryEmbedding`,[AX]],[`ScatterND`,[WZ,UZ]],[`Sigmoid`,[nq]],[`Sin`,[aq]],[`Sinh`,[oq]],[`Slice`,[CQ,wQ]],[`SkipLayerNormalization`,[hQ]],[`Split`,[TX,EX]],[`Sqrt`,[sq]],[`Softmax`,[OQ,kQ]],[`Sub`,[Mq]],[`Tan`,[cq]],[`Tanh`,[uq]],[`ThresholdedRelu`,[mq,WK]],[`Tile`,[FQ]],[`Transpose`,[sG,cG]],[`Where`,[zQ]]])}),UQ,WQ=Z(()=>{LH(),ZU(),$W(),UQ=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,i){wH(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let s=[];for(let e of t)s.push({binding:s.length,resource:{buffer:e.buffer}});for(let e of n)s.push({binding:s.length,resource:{buffer:e.buffer}});i&&s.push({binding:s.length,resource:i});let c=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:s,label:e.programInfo.name});if(this.backend.sessionStatus===`capturing`){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}o.setPipeline(e.computePipeline),o.setBindGroup(0,c),o.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===`at-passes`)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),TH(e.programInfo.name)}dispose(){}build(e,t){wH(e.name);let n=this.backend.device,r=[];[{feature:`shader-f16`,extension:`f16`},{feature:`subgroups`,extension:`subgroups`}].forEach(e=>{n.features.has(e.feature)&&r.push(`enable ${e.extension};`)});let i=QW(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${r.join(`
15594
+ }`},BQ=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,i=e[1].dataType,a=!(Q.areEqual(t,n)&&Q.areEqual(n,r)),o=t,s=Q.size(t);if(a){let e=tW.calcShape(tW.calcShape(t,n,!1),r,!1);if(!e)throw Error(`Can't perform where op on the given tensors`);o=e,s=Q.size(o)}let c=Math.ceil(s/4);return{name:`Where`,shaderCache:{inputDependencies:[`rank`,`rank`,`rank`]},getShaderSource:t=>zQ(t,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(s/64/4)},programUniforms:[{type:12,data:c},...UW(r,t,n,o)]})}},VQ=e=>{e.compute(BQ(e.inputs))}}),UQ,WQ=Z(()=>{dK(),bK(),TK(),kK(),Tq(),zq(),Kq(),zJ(),ZJ(),tY(),sY(),yY(),TY(),OY(),NY(),LY(),HY(),qY(),QY(),pX(),zX(),WX(),JX(),ZX(),rZ(),xX(),pZ(),NZ(),RZ(),HZ(),qZ(),oK(),mQ(),NX(),vQ(),DQ(),MQ(),kX(),RQ(),dG(),xq(),HQ(),UQ=new Map([[`Abs`,[MK]],[`Acos`,[NK]],[`Acosh`,[PK]],[`Add`,[kq]],[`ArgMax`,[lK,uK]],[`ArgMin`,[cK,uK]],[`Asin`,[FK]],[`Asinh`,[IK]],[`Atan`,[LK]],[`Atanh`,[RK]],[`Attention`,[yK]],[`AveragePool`,[wZ,CZ]],[`BatchNormalization`,[wK]],[`BiasAdd`,[OK]],[`BiasSplitGelu`,[wq]],[`Cast`,[BK,zK]],[`Ceil`,[UK]],[`Clip`,[HK]],[`Concat`,[Wq,Gq]],[`Conv`,[RJ,PJ]],[`ConvTranspose`,[XJ,KJ]],[`Cos`,[WK]],[`Cosh`,[GK]],[`CumSum`,[$J,eY]],[`DepthToSpace`,[aY,oY]],[`DequantizeLinear`,[IZ,LZ]],[`Div`,[Aq]],[`Einsum`,[_Y,vY]],[`Elu`,[qK,KK]],[`Equal`,[jq]],[`Erf`,[YK]],[`Exp`,[XK]],[`Expand`,[wY]],[`FastGelu`,[DY]],[`Floor`,[ZK]],[`FusedConv`,[RJ,PJ]],[`Gather`,[MY,jY]],[`GatherElements`,[KY,GY]],[`GatherBlockQuantized`,[BY,VY]],[`GatherND`,[FY,IY]],[`Gelu`,[QK]],[`Gemm`,[ZY,XY]],[`GlobalAveragePool`,[DZ,EZ]],[`GlobalMaxPool`,[MZ,jZ]],[`Greater`,[Fq]],[`GreaterOrEqual`,[Lq]],[`GridSample`,[dX,fX]],[`GroupQueryAttention`,[RX]],[`HardSigmoid`,[oq,aq]],[`InstanceNormalization`,[UX]],[`LayerNormalization`,[qX]],[`LeakyRelu`,[$K,KK]],[`Less`,[Iq]],[`LessOrEqual`,[Rq]],[`Log`,[_q]],[`MatMul`,[XX]],[`MatMulNBits`,[tZ,nZ]],[`MaxPool`,[kZ,AZ]],[`Mul`,[Mq]],[`MultiHeadAttention`,[bX,gX]],[`Neg`,[tq]],[`Not`,[eq]],[`Pad`,[fZ]],[`Pow`,[Nq]],[`QuickGelu`,[bq,KK]],[`Range`,[VZ]],[`Reciprocal`,[nq]],[`ReduceMin`,[tK]],[`ReduceMean`,[XG]],[`ReduceMax`,[eK]],[`ReduceSum`,[rK]],[`ReduceProd`,[nK]],[`ReduceL1`,[ZG]],[`ReduceL2`,[QG]],[`ReduceLogSum`,[aK]],[`ReduceLogSumExp`,[$G]],[`ReduceSumSquare`,[iK]],[`Relu`,[rq]],[`Resize`,[fQ,pQ]],[`RotaryEmbedding`,[MX]],[`ScatterND`,[KZ,GZ]],[`Sigmoid`,[iq]],[`Sin`,[sq]],[`Sinh`,[cq]],[`Slice`,[TQ,EQ]],[`SkipLayerNormalization`,[_Q]],[`Split`,[DX,OX]],[`Sqrt`,[lq]],[`Softmax`,[AQ,jQ]],[`Sub`,[Pq]],[`Tan`,[uq]],[`Tanh`,[fq]],[`ThresholdedRelu`,[gq,KK]],[`Tile`,[LQ]],[`Transpose`,[lG,uG]],[`Where`,[VQ]]])}),GQ,KQ=Z(()=>{zH(),$U(),tG(),GQ=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,i){EH(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let s=[];for(let e of t)s.push({binding:s.length,resource:{buffer:e.buffer}});for(let e of n)s.push({binding:s.length,resource:{buffer:e.buffer}});i&&s.push({binding:s.length,resource:i});let c=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:s,label:e.programInfo.name});if(this.backend.sessionStatus===`capturing`){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}o.setPipeline(e.computePipeline),o.setBindGroup(0,c),o.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===`at-passes`)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),DH(e.programInfo.name)}dispose(){}build(e,t){EH(e.name);let n=this.backend.device,r=[];[{feature:`shader-f16`,extension:`f16`},{feature:`subgroups`,extension:`subgroups`}].forEach(e=>{n.features.has(e.feature)&&r.push(`enable ${e.extension};`)});let i=eG(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${r.join(`
15595
15595
  `)}
15596
15596
  ${i.additionalImplementations}
15597
- ${a}`,s=n.createShaderModule({code:o,label:e.name});XU(`verbose`,()=>`[WebGPU] ${e.name} shader code: ${o}`);let c=n.createComputePipeline({compute:{module:s,entryPoint:`main`},layout:`auto`,label:e.name});return TH(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e==`number`?e:e.x,n=typeof e==`number`?1:e.y||1,r=typeof e==`number`?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw Error(`Total dispatch size exceeds WebGPU maximum.`);return[o,o,o]}else return[o,o,1]}}}),GQ={};LV(GQ,{WebGpuBackend:()=>YQ});var KQ,qQ,JQ,YQ,XQ=Z(()=>{LH(),VU(),ZU(),oW(),NW(),HQ(),WQ(),KQ=(e,t)=>{if(t.length!==e.length)throw Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r<e.length;++r){let i=e[r].dataType;switch(t[r]){case`none`:n.push(``);break;case`type`:n.push(`${i}`);break;case`rank`:{let t=e[r].dims.length;n.push(`${i};${t}`);break}case`dims`:{let t=e[r].dims.join(`,`);n.push(`${i};${t}`);break}default:throw Error(`unsupported input dependency: ${t[r]}`)}}return n.join(`|`)},qQ=(e,t,n)=>{let r=e.name;return e.shaderCache?.hint&&(r+=`[`+e.shaderCache.hint+`]`),r+=`:`+n+`:${KQ(t,e.shaderCache?.inputDependencies??Array(t.length).fill(`dims`))}`,r},JQ=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},YQ=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus=`default`,this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw Error(`currentKernelCustomData(): currentKernelId is null. (should not happen)`);let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i(`chromium-experimental-timestamp-query-inside-passes`)||i(`timestamp-query`),i(`shader-f16`),i(`subgroups`),this.device=await t.requestDevice(r),this.adapterInfo=new JQ(t.info||await t.requestAdapterInfo()),this.gpuDataManager=MW(this),this.programManager=new UQ(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,JU(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<`u`&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||=this.device.createCommandEncoder(),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType===`at-passes`&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&=(this.computePassEncoder.end(),null)}flush(){if(!this.commandEncoder)return;wH(),this.endComputePass();let e;this.queryType!==`none`&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==`none`&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let r=n[e],i=r.kernelId,a=this.kernels.get(i),o=a.kernelType,s=a.kernelName,c=r.programName,l=r.inputTensorViews,u=r.outputTensorViews,d=t[e*2],f=t[e*2+1];typeof this.queryTimeBase>`u`&&(this.queryTimeBase=d);let p=Number(d-this.queryTimeBase),m=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(p)||!Number.isSafeInteger(m))throw RangeError(`incorrect timestamp range`);if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map(e=>({dims:e.dims,dataType:PU(e.dataType)})),outputsMetadata:u.map(e=>({dims:e.dims,dataType:PU(e.dataType)})),kernelId:i,kernelType:o,kernelName:s,programName:c,startTime:p,endTime:m});else{let e=``;l.forEach((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${PU(t.dataType)}, `});let t=``;u.forEach((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${PU(e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${s}|${c}" ${e}${t}start time: ${p} ns, execution time: ${m-p} ns`)}SH(`GPU`,`${c}::${d}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),TH()}run(e,t,n,r,i,a){wH(e.name);let o=[];for(let e=0;e<t.length;++e){let n=t[e].data;if(n===0)continue;let r=this.gpuDataManager.get(n);if(!r)throw Error(`no GPU data for input: ${n}`);o.push(r)}let{outputs:s,dispatchGroup:c,programUniforms:l}=e.getRunData(t),u=n.length===0?s.map((e,t)=>t):n;if(u.length!==s.length)throw Error(`Output size ${u.length} must be equal to ${s.length}.`);let d=[],f=[];for(let e=0;e<s.length;++e){if(!Number.isInteger(u[e])||u[e]<-3||u[e]>=a)throw Error(`Invalid output index: ${u[e]}`);if(u[e]===-3)continue;let t=u[e]===-1,n=u[e]===-2,o=t||n?i(s[e].dataType,s[e].dims):r(u[e],s[e].dataType,s[e].dims);if(d.push(o),o.data===0)continue;let c=this.gpuDataManager.get(o.data);if(!c)throw Error(`no GPU data for output: ${o.data}`);if(t&&this.temporaryData.push(c),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(c)}f.push(c)}if(o.length!==t.length||f.length!==d.length){if(f.length===0)return TH(e.name),d;throw Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let p;if(l){let e=0,t=[];l.forEach(n=>{let r=typeof n.data==`number`?[n.data]:n.data;if(r.length===0)return;let i=n.type===10?2:4,a,o;n.type===10?(o=r.length>4?16:r.length>2?8:r.length*i,a=r.length>4?16:i*r.length):(o=r.length<=2?r.length*i:16,a=16),e=Math.ceil(e/o)*o,t.push(e);let s=n.type===10?8:4;e+=r.length>4?Math.ceil(r.length/s)*a:r.length*i}),e=Math.ceil(e/16)*16;let n=new ArrayBuffer(e);l.forEach((e,r)=>{let i=t[r],a=typeof e.data==`number`?[e.data]:e.data;if(e.type===6)new Int32Array(n,i,a.length).set(a);else if(e.type===12)new Uint32Array(n,i,a.length).set(a);else if(e.type===10)new Uint16Array(n,i,a.length).set(a);else if(e.type===1)new Float32Array(n,i,a.length).set(a);else throw Error(`Unsupported uniform type: ${PU(e.type)}`)});let r=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(r.buffer,0,n,0,e),this.gpuDataManager.release(r.id),p={offset:0,size:e,buffer:r.buffer}}let m=this.programManager.normalizeDispatchGroupSize(c),h=m[1]===1&&m[2]===1,g=qQ(e,t,h),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),XU(`info`,()=>`[artifact] key: ${g}, programName: ${e.name}`)),l&&_.uniformVariablesInfo){if(l.length!==_.uniformVariablesInfo.length)throw Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${l.length} in program "${_.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,r=typeof t.data==`number`?1:t.data.length,[i,a]=_.uniformVariablesInfo[e];if(n!==i||r!==a)throw Error(`Uniform variable ${e} mismatch: expect type ${i} with size ${a}, got type ${n} with size ${r} in program "${_.programInfo.name}".`)}}if(XU(`info`,()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!==`none`||this.sessionStatus===`capturing`){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:d};this.pendingKernels.push(e),this.sessionStatus===`capturing`&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,o,f,m,p),TH(e.name),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=VQ.get(e);if(!i)throw Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,o=r.kernelEntry,s=r.attributes;if(this.currentKernelId!==null)throw Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&=(s[1]=s[0](s[1]),void 0),XU(`info`,()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(`validation`),o(t,s[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{c&&n.push(this.device.popErrorScope().then(e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[o,n]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(e=>this.gpuDataManager.unregisterExternalBuffer(e[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await AW(this,e,t);return aW(r.buffer,n)}}writeTimestamp(e){this.queryType===`inside-passes`&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType=`none`,(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>`u`?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(`chromium-experimental-timestamp-query-inside-passes`)?this.queryType=`inside-passes`:this.device.features.has(`timestamp-query`)&&(this.queryType=`at-passes`),this.queryType!==`none`&&typeof this.querySet>`u`&&(this.querySet=this.device.createQuerySet({type:`timestamp`,count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){XU(`info`,`captureBegin`),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=`capturing`}captureEnd(){XU(`info`,`captureEnd`),this.flush(),this.sessionStatus=`default`}replay(){XU(`info`,`replay`),this.sessionStatus=`replaying`;let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r<n;r++){let n=this.getComputePassEncoder(),i=e[r];this.writeTimestamp(this.pendingDispatchNumber*2),n.setPipeline(i.computePipeline),n.setBindGroup(0,i.bindGroup),n.dispatchWorkgroups(...i.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!==`none`&&this.pendingKernels.push(t[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType===`at-passes`)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=`default`}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),ZQ={};LV(ZQ,{init:()=>e$});var QQ,$Q,e$,t$=Z(()=>{VU(),ZU(),iW(),SW(),QQ=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(this.dataType!==1)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(Q.size(t)!==Q.size(this.dims))throw Error(`Invalid new shape`);return new e(this.module,this.dataType,this.data,t)}},$Q=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=r===4?`i32`:`i64`;this.opKernelContext=Number(e.getValue(r*i++,a));let o=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,`*`)),this.customDataSize=Number(e.getValue(r*i++,a));let s=[];for(let t=0;t<o;t++){let t=Number(e.getValue(r*i++,a)),n=Number(e.getValue(r*i++,`*`)),o=Number(e.getValue(r*i++,a)),c=[];for(let t=0;t<o;t++)c.push(Number(e.getValue(r*i++,a)));s.push(new QQ(e,t,n,c))}this.inputs=s}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(e=>typeof e==`number`?this.inputs[e]:e)??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,(e,t,n)=>new QQ(this.module,t,this.output(e,n),n),(e,t)=>{let n=FU(e,t);if(!n)throw Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new QQ(this.module,e,r,t)},this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=n===4?`i32`:`i64`,i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e<t.length;e++)this.module.setValue(i+n*(e+1),t[e],r);return this.module._JsepOutput(this.opKernelContext,e,i)}catch(n){throw Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`)}finally{this.module.stackRestore(n)}}},e$=async(e,t,n,r)=>{let i=t.jsepInit;if(!i)throw Error(`Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.`);if(e===`webgpu`){let e=(XQ(),zV(GQ)).WebGpuBackend,a=new e;await a.initialize(n,r),i(`webgpu`,[a,e=>a.alloc(Number(e)),e=>a.free(e),(e,n,r,i=!1)=>{if(i)XU(`verbose`,()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(e)}, dst=${Number(n)}, size=${Number(r)}`),a.memcpy(Number(e),Number(n));else{XU(`verbose`,()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(e)}, gpuDataId=${Number(n)}, size=${Number(r)}`);let i=t.HEAPU8.subarray(Number(e>>>0),Number(e>>>0)+Number(r));a.upload(Number(n),i)}},async(e,n,r)=>{XU(`verbose`,()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${e}, dataOffset=${n}, size=${r}`),await a.download(Number(e),()=>t.HEAPU8.subarray(Number(n)>>>0,Number(n+r)>>>0))},(e,n,r)=>a.createKernel(e,Number(n),r,t.UTF8ToString(t._JsepGetNodeName(Number(n)))),e=>a.releaseKernel(e),(e,n,r,i)=>{XU(`verbose`,()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${e}, contextDataOffset=${n}`);let o=new $Q(t,a,Number(n));return a.computeKernel(Number(e),o,i)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let e=new xW(n);i(`webnn`,[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i,a)=>e.ensureTensor(t,n,r,i,a),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n),(t,n)=>e.registerMLContext(t,n),!!n.trace])}}}),n$,r$,i$,a$,o$,s$,c$,l$,u$,d$,f$,p$,m$,h$=Z(()=>{LH(),TU(),MU(),VU(),yU(),CU(),UU(),n$=(e,t)=>{vU()._OrtInit(e,t)!==0&&SU(`Can't initialize onnxruntime.`)},r$=async e=>{n$(e.wasm.numThreads,LU(e.logLevel))},i$=async(e,t)=>{vU().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`);{let r=(t$(),zV(ZQ)).init;t===`webgpu`&&await r(`webgpu`,vU(),e,n),t===`webnn`&&await r(`webnn`,vU(),e)}},a$=new Map,o$=e=>{let t=vU(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&SU(`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)}},s$=(e,t)=>{let n=vU(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&SU(`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<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},c$=e=>{let t=vU(),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]},l$=async(e,t)=>{let n,r,i=vU();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=c$(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await jU(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(HU(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&&SU(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=o$(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=s$(a,t);e===0&&SU(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:PU(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=s$(a,n+e);r===0&&SU(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:PU(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&SU(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>BU(e))}),a$.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&&SU(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&SU(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&SU(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},u$=e=>{let t=vU(),n=a$.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&&SU(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&SU(`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&&SU(`Can't release session.`),a$.delete(e)},d$=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=vU(),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=FU(NU(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=FU(NU(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,NU(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;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,bU(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=NU(l);m=FU(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(NU(l),p,m,g,u.length,BU(f));e===0&&SU(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},f$=async(e,t,n,r,i,a)=>{let o=vU(),s=o.PTR_SIZE,c=a$.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]=wU(a),EH(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await d$(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await d$(i[t],b,x,e,d[r[t]],h+r[t],p);DH(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(w+e*s,y[e],`*`),o.setValue(T+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(E+e*s,b[e],`*`),o.setValue(D+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);EH(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&SU(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&SU(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&SU(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}DH(`wasm bindInputsOutputs`),a$.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,E,_):await o._OrtRun(l,T,w,h,D,g,E,_),c!==0&&SU(`failed to call OrtRun().`);let C=[],O=[];EH(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(E+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&SU(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&SU(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&SU(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=PU(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;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=FU(a,g);if(r===void 0||!RU(u))throw Error(`Unsupported data type: ${u}`);l=!0,C.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&SU(`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(FU(a,g)===void 0||!zU(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(IU(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&&SU(`Can't clear bound outputs.`),a$.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(O))C[e][2]=t;return DH(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),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))}},p$=e=>{let t=vU(),n=a$.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&SU(`Can't get an profile file name.`),t._OrtFree(i)},m$=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),g$,_$,v$,y$,b$,x$,S$,C$,w$,T$,E$,D$,O$,k$,A$,j$,M$,N$,P$=Z(()=>{LH(),h$(),yU(),lU(),g$=()=>!!QV.wasm.proxy&&typeof document<`u`,v$=!1,y$=!1,b$=!1,C$=new Map,w$=(e,t)=>{let n=C$.get(e);n?n.push(t):C$.set(e,[t])},T$=()=>{if(v$||!y$||b$||!_$)throw Error(`worker not ready`)},E$=e=>{switch(e.data.type){case`init-wasm`:v$=!1,e.data.err?(b$=!0,S$[1](e.data.err)):(y$=!0,S$[0]()),x$&&=(URL.revokeObjectURL(x$),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=C$.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},D$=async()=>{if(!y$){if(v$)throw Error(`multiple calls to 'initWasm()' detected.`);if(b$)throw Error(`previous call to 'initWasm()' failed.`);if(v$=!0,g$())return new Promise((e,t)=>{_$?.terminate(),oU().then(([n,r])=>{try{_$=r,_$.onerror=e=>t(e),_$.onmessage=E$,S$=[e,t];let i={type:`init-wasm`,in:QV};!i.in.wasm.wasmPaths&&(n||XH)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm`,``+import.meta.url).href}),_$.postMessage(i),x$=n}catch(e){t(e)}},t)});try{await _U(QV.wasm),await r$(QV),y$=!0}catch(e){throw b$=!0,e}finally{v$=!1}}},O$=async e=>{if(g$())return T$(),new Promise((t,n)=>{w$(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:QV}};_$.postMessage(r)});await i$(QV,e)},k$=async e=>g$()?(T$(),new Promise((t,n)=>{w$(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};_$.postMessage(r,[e.buffer])})):c$(e),A$=async(e,t)=>{if(g$()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return T$(),new Promise((n,r)=>{w$(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),_$.postMessage(i,a)})}else return l$(e,t)},j$=async e=>{if(g$())return T$(),new Promise((t,n)=>{w$(`release`,[t,n]);let r={type:`release`,in:e};_$.postMessage(r)});u$(e)},M$=async(e,t,n,r,i,a)=>{if(g$()){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 T$(),new Promise((i,o)=>{w$(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};_$.postMessage(c,m$(s))})}else return f$(e,t,n,r,i,a)},N$=async e=>{if(g$())return T$(),new Promise((t,n)=>{w$(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};_$.postMessage(r)});p$(e)}}),F$,I$,L$,R$=Z(()=>{LH(),P$(),VU(),RH(),UU(),F$=(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()}`)}},I$=e=>{switch(e[3]){case`cpu`:return new bH(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!RU(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return bH.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!zU(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return bH.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},L$=class{async fetchModelAndCopyToWasmMemory(e){return k$(await HU(e))}async loadModel(e,t){wH();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await A$(n,t),TH()}async dispose(){return j$(this.sessionId)}async run(e,t,n){wH();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)=>F$(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?F$(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await M$(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??I$(l[e]);return TH(),u}startProfiling(){}endProfiling(){N$(this.sessionId)}}}),z$={};LV(z$,{OnnxruntimeWebAssemblyBackend:()=>V$,initializeFlags:()=>B$,wasmBackend:()=>H$});var B$,V$,H$,U$=Z(()=>{LH(),P$(),R$(),B$=()=>{(typeof QV.wasm.initTimeout!=`number`||QV.wasm.initTimeout<0)&&(QV.wasm.initTimeout=0);let e=QV.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.`),QV.wasm.simd=!1),typeof QV.wasm.proxy!=`boolean`&&(QV.wasm.proxy=!1),typeof QV.wasm.trace!=`boolean`&&(QV.wasm.trace=!1),typeof QV.wasm.numThreads!=`number`||!Number.isInteger(QV.wasm.numThreads)||QV.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)QV.wasm.numThreads=1;else{let e=typeof navigator>`u`?IV(`node:os`).cpus().length:navigator.hardwareConcurrency;QV.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},V$=class{async init(e){B$(),await D$(),await O$(e)}async createInferenceSessionHandler(e,t){let n=new L$;return await n.loadModel(e,t),n}},H$=new V$});LH(),LH(),LH();var W$=`1.24.3`;{let e=(U$(),zV(z$)).wasmBackend;HV(`webgpu`,e,5),HV(`webnn`,e,5),HV(`cpu`,e,10),HV(`wasm`,e,10)}Object.defineProperty(QV.versions,"web",{value:W$,enumerable:!0});var G$=class{constructor(e,t){this.runner=e,this.config=t}},K$=class extends G${constructor(e,t){super(e,t),this.store=new EV,this.cachedSize=null,this.graph=t.graph,this.params=t.params??{}}get size(){return this.cachedSize??this.inferSize()}reset(e){this.store.reset()}compute(e){let t=this.evaluate(e);if(this.cachedSize===null)return this.cachedSize=t.length,t;if(t.length===this.cachedSize)return t;let n=new Float32Array(this.cachedSize);return n.set(t.subarray(0,Math.min(t.length,this.cachedSize))),n}evaluate(e){let t=DV(this.graph,{runner:this.runner,state:e,params:this.params},this.store);if(t instanceof Float32Array)return t;if(typeof t==`number`)return new Float32Array([t]);if(typeof t==`boolean`)return new Float32Array([+!!t]);if(t instanceof Uint8Array){let e=new Float32Array(t.length);for(let n=0;n<t.length;n++)e[n]=t[n];return e}return new Float32Array}inferSize(){this.runner.getContext();let e={jointPos:new Float32Array(this.runner.getNumActions())};return this.compute(e),this.cachedSize??0}},q$=class{constructor(e,t={}){this.motionCache=new Map,this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=e.policy_num_actions??this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(let t of Object.values(this.obsGroups))for(let n of t)n.reset&&n.reset(e);if(e){for(let[t,n]of Object.entries(this.historyConfig))if(n.steps>1){let r=this.buildFrame(this.obsGroups[t]??[],e),i=this.historyBuffers[t];for(let e=0;e<n.steps;e++)i.set(r,e*r.length)}}}update(e){this.policyModule?.update();for(let t of Object.values(this.obsGroups))for(let n of t)n.update&&n.update(e)}collectObservationsByKey(e){this.update(e);let t={};for(let[n,r]of Object.entries(this.obsGroups)){let i=this.historyConfig[n];if(i&&i.steps>1){let i=this.buildFrame(r,e),a=this.historyBuffers[n];for(let e=a.length-1;e>=i.length;e--)a[e]=a[e-i.length];a.set(i,0),t[n]=new Float32Array(a)}else t[n]=this.buildFrame(r,e)}return t}collectObservations(e){let t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];let n=Object.keys(t)[0];return n?t[n]:new Float32Array}async preloadAll(){let e=[];for(let t of Object.values(this.obsGroups))for(let n of t)typeof n.preload==`function`&&e.push(n.preload());await Promise.all(e)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];let e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(e=>({...e}));let e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(e=>({...e})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}getConfig(){return this.config}getMotionData(e){let t=this.motionCache.get(e);if(t)return t;let n=this.options.motions?.find(t=>t.name===e),r=n?UB(n.data):Promise.resolve(null);return this.motionCache.set(e,r),r}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){let t=this.options.policyModules??{},n=this.config.policy_module,r=n?t[n]:t.default;if(n&&!r)throw Error(`Unknown policy module: ${n}`);if(!r)return null;let i=new r(this.config);return await i.init(e),i}buildObservationGroups(){let e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;let n=t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new K$(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);return new r(this,t)};for(let[r,i]of Object.entries(t)){if(Array.isArray(i)){let e=i.map(n);this.registerGroup(r,e,i);continue}if(i&&typeof i==`object`){let t=i;if(Array.isArray(t.components)){let n=t.components.map(t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new K$(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);let i={...t,history_steps:1};return new r(this,i)}),i=Math.max(1,Math.floor(t.history_steps??1)),a=!!t.interleaved;this.registerGroup(r,n,t.components,{steps:i,interleaved:a})}}}this.obsGroups.policy?this.defaultObsKey=`policy`:this.obsGroups.observation?this.defaultObsKey=`observation`:this.obsGroups.obs_history?this.defaultObsKey=`obs_history`:this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,n,r){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((e,t)=>({name:n[t]?.name??`obs_${t}`,size:e.size}));let i=this.obsLayouts[e].reduce((e,t)=>e+t.size,0);r&&r.steps>1?(this.historyConfig[e]=r,this.historyBuffers[e]=new Float32Array(i*r.steps),this.obsSizes[e]=i*r.steps):this.obsSizes[e]=i}buildFrame(e,t){let n=e.map(e=>{let n=e.compute(t),r=n instanceof Float32Array?n:Float32Array.from(n);if(r.length!==e.size)throw Error(`Observation size mismatch: expected ${e.size}, got ${r.length}`);return r}),r=n.reduce((e,t)=>e+t.length,0),i=new Float32Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i}normalizeArray(e,t,n){let r=new Float32Array(t);for(let i=0;i<t;i++)r[i]=typeof e[i]==`number`?e[i]:n;return r}};QV.wasm.proxy=!1,QV.wasm.numThreads=1,typeof __ORT_CDN_BASE__<`u`&&(QV.wasm.wasmPaths=__ORT_CDN_BASE__);var J$=class{constructor(e,t){this.bytes=e,this.session=null;let n=t?.in_keys??[`policy`],r=t?.out_keys??[`action`];this.configuredInKeys=n.map(e=>Array.isArray(e)?e.join(`,`):e),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(e=>Array.isArray(e)?e.join(`,`):e),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}async init(){this.session=await jH.create(this.bytes,{executionProviders:[`wasm`],graphOptimizationLevel:`all`}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}initInput(){let e={};return this.isRecurrent&&(e.is_init=new bH(`bool`,[!0],[1]),e.adapt_hx=new bH(`float32`,new Float32Array(128),[1,128])),this.inKeys.includes(`time_step`)&&(e.time_step=new bH(`float32`,new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw Error(`OnnxModule not initialized.`);let t={};for(let n=0;n<this.inKeys.length;n++){let r=this.inKeys[n],i=this.session.inputNames[n];if(!i||!e[r])throw Error(`Missing ONNX input for key: ${r}`);t[i]=e[r]}let n=await this.session.run(t),r={};for(let e=0;e<this.outKeys.length;e++){let t=this.outKeys[e],i=this.session.outputNames[e];i&&n[i]&&(r[t]=n[i])}let i={};return this.isRecurrent&&r[`next,adapt_hx`]&&(i.is_init=new bH(`bool`,[!1],[1]),i.adapt_hx=r[`next,adapt_hx`]),[r,i]}dispose(){this.session?.release?.(),this.session=null}inferInputKeys(){if(!this.session)return;let e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(e=>this.configuredInKeys.includes(e)?e:e===`obs`&&this.configuredInKeys.includes(`policy`)?`policy`:e)}},Y$=class{constructor(e,t,n,r){this.mujoco=e,this.mjModel=t,this.mjData=n;let i=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(let e of r){let n=i.indexOf(e);if(n<0)throw Error(`Joint "${e}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[n]),this.qvelAdr.push(t.jnt_dofadr[n]),this.jointIndices.push(n)}this.numActions=r.length,this.ctrlAdr=this.buildCtrlAdr()}build(){let e=this.mjData.qpos,t=this.mjData.qvel,n=new Float32Array(this.numActions),r=new Float32Array(this.numActions);for(let i=0;i<this.numActions;i++)n[i]=e[this.qposAdr[i]],r[i]=t[this.qvelAdr[i]];return{jointPos:n,jointVel:r,rootPos:new Float32Array([e[0],e[1],e[2]]),rootQuat:new Float32Array([e[3],e[4],e[5],e[6]]),rootLinVel:new Float32Array([t[0],t[1],t[2]]),rootAngVel:new Float32Array([t[3],t[4],t[5]])}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;let n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[],o=[],s=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(this.ctrlAdr[e]),a.push(this.qposAdr[e]),o.push(this.qvelAdr[e]),s.push(e));return i.length===0?null:{ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s}}getCtrlMappingByActuatorNames(e){let t=this.getActuatorNames(this.mjModel),n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(e),a.push(i.length-1));return i.length>0?{ctrlAdr:i,actionIndices:a}:null}getActuatorNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.nu;i++){let a=e.name_actuatoradr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;let e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let n=0;n<this.mjModel.nu;n++){let r=this.mjModel.actuator_trntype[n];e===void 0||r===e?t.push(this.mjModel.actuator_trnid[2*n]):t.push(-1)}let n=[];for(let e of this.jointIndices){let r=t.findIndex(t=>t===e);if(r<0)return null;n.push(r)}return n}getJointNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;let s=n.decode(t.subarray(a,o));!s&&i===0&&(s=`floating_base_joint`),r.push(s)}return r}},X$=class{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}},Z$=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},Q$=class extends X${constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.tracking=new Z$(n)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}},$$=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},e1=class extends X${constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.locomotion=new $$(n)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}},t1=class{constructor(e){this.config=e}};function n1(e,t){return e+Math.random()*(t-e)}function r1(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}function i1(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}var a1=class extends t1{constructor(e){super(e),this.mutations=e.mutations??[]}onReset(e){let{mjModel:t,mjData:n}=e;if(!(!t||!n))for(let e of this.mutations)switch(e.target){case`joint_qpos`:this.applyJointOffset(t,n,e,`qpos`);break;case`joint_qvel`:this.applyJointOffset(t,n,e,`qvel`);break;case`freejoint_pos`:this.applyFreejointPos(t,n,e);break;case`freejoint_yaw`:this.applyFreejointYaw(t,n,e);break}}resolveJointIndices(e,t){let n=t.select??{};if(n.joint_ids&&n.joint_ids.length>0)return n.joint_ids.filter(t=>t>=0&&t<e.njnt);let r=r1(e);return n.joint_names&&n.joint_names.length>0?n.joint_names.map(e=>this.findJointIndex(r,e,n.entity_name)).filter(e=>e!==null):r.map((e,t)=>({name:e,idx:t})).filter(({name:t,idx:r})=>e.jnt_type[r]===0?!1:n.entity_name?t===n.entity_name||t.startsWith(`${n.entity_name}/`):!0).map(({idx:e})=>e)}findJointIndex(e,t,n){let r=e.indexOf(t);if(r>=0)return r;if(n){let r=e.indexOf(`${n}/${t}`);if(r>=0)return r}let i=e.map((e,t)=>({name:e,idx:t})).filter(({name:e})=>e===t||e.endsWith(`/${t}`));if(i.length===1)return i[0].idx;if(n){let e=i.find(({name:e})=>e===n||e.startsWith(`${n}/`));if(e)return e.idx}return null}applyJointOffset(e,t,n,r){if(n.sample.dist!==`uniform`)return;let{low:i,high:a}=n.sample;for(let o of this.resolveJointIndices(e,n)){let s=e.jnt_type[o];if(!(s!==2&&s!==3))if(r===`qpos`){let r=e.jnt_qposadr[o];if(t.qpos[r]+=n1(i,a),n.clip_to_limits&&e.jnt_limited[o]){let n=e.jnt_range[o*2],i=e.jnt_range[o*2+1];t.qpos[r]=Math.min(Math.max(t.qpos[r],n),i)}}else t.qvel[e.jnt_dofadr[o]]+=n1(i,a)}}applyFreejointPos(e,t,n){if(n.sample.dist!==`uniform_xyz`)return;let r=i1(e);if(r<0)return;let i=e.jnt_qposadr[r];t.qpos[i]+=n1(n.sample.x[0],n.sample.x[1]),t.qpos[i+1]+=n1(n.sample.y[0],n.sample.y[1]),t.qpos[i+2]+=n1(n.sample.z[0],n.sample.z[1])}applyFreejointYaw(e,t,n){if(n.sample.dist!==`uniform`)return;let r=i1(e);if(r<0)return;let i=e.jnt_qposadr[r]+3,a=n1(n.sample.low,n.sample.high),o=Math.cos(a/2),s=Math.sin(a/2),c=t.qpos[i],l=t.qpos[i+1],u=t.qpos[i+2],d=t.qpos[i+3];t.qpos[i]=o*c-s*d,t.qpos[i+1]=o*l+s*u,t.qpos[i+2]=o*u-s*l,t.qpos[i+3]=o*d+s*c}};function o1(e){return`kind`in e&&e.kind===`event`&&Array.isArray(e.mutations)}var s1=class{constructor(e,t){this.terms=[];for(let n of e){if(o1(n)){this.terms.push(new a1(n));continue}let e=t[n.name];if(!e){console.warn(`[EventManager] Unknown event type: ${n.name}`);continue}this.terms.push(new e(n))}}onReset(e){for(let t of this.terms)t.onReset(e)}get size(){return this.terms.length}},c1={};function l1(e){return typeof e==`object`&&!!e&&typeof e.setSelectedMotion==`function`}var u1=class extends Error{constructor(){super(`This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory.`),this.name=`WasmMemoryLimitError`}};function d1(e){let t=e instanceof Error?e.message:String(e);return t.includes(`MjModel loading returned null`)||t.includes(`Could not allocate memory`)||t.includes(`memory allocation failed`)||t.includes(`bad_alloc`)}var f1=class{constructor(e,t){this.render=()=>{if(this.commandManager.updateDebugVisuals(),this.mjData&&AB(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){WN(this.camera,this.lights);for(let[e,t]of this.lastSimState.bodies){let n=this.bodies[e];n&&(n.position.copy(t.position),n.quaternion.copy(t.quaternion))}UN(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&QN({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{let{width:e,height:t}=this.getSize();this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)},this.mujoco=e,this.container=t,this.commandManager=new rV,this.scenePlugins={},this.policyPlugins={};let n=`/working`;try{this.mujoco.FS.mkdir(n)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&console.warn(`Failed to create /working directory:`,e)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:`.`},n)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&e.code!==`EBUSY`&&console.warn(`Failed to mount MEMFS at /working:`,e)}let{width:r,height:i}=this.getSize();this.scene=new nC,this.scene.name=`scene`,this.camera=new GS(45,r/i,.001,1e3),this.camera.name=`PerspectiveCamera`,this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new hN({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(r,i),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=2,this.renderer.outputColorSpace=Rv,this.renderer.toneMapping=4,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported(`immersive-vr`).then(e=>{e&&(this.vrButton=zN.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new EN(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener(`resize`,this.onWindowResize),`ResizeObserver`in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:$N()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.policyCtrlDt=null,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.initialQpos=null,this.initialQvel=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.currentSplatTransform={},this.cameraState={trackBodyId:null,prevBodyPos:null}}async loadEnvironment(e){this.scenePlugins=e.plugins??{},this.terrainData=e.terrainData??null,e.events&&e.events.length>0?(this.eventManager=new s1(e.events,{...c1,...this.scenePlugins.events}),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&=(Cz(this.splatMesh,this.scene),null),this.colliderMesh&&=(TB(this.colliderMesh,this.scene),null),this.initializeCommands(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,await this.buildSceneFromMjz(e.model),e.splat&&await this.applySplat(e.splat),await this.loadPolicyConfig(e.policy??null),this.applyViewerConfig(e.viewer??null),this.running=!0,this.startLoop()}initializeCommands(){this.commandManager.clear()}initializeCommandsFromConfig(e,t){this.commandManager.initialize(e,t,this.policyPlugins.commands),console.log(`[mjswanRuntime] Commands loaded from policy config:`,Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log(`[mjswanRuntime] Simulation reset`)}async setSelectedMotion(e){let t=this.commandManager.getTerm(`motion`);if(!l1(t))return!1;let n=await t.setSelectedMotion(e);return n&&this.resetSimulation(),n}getSelectedMotionName(){let e=this.commandManager.getTerm(`motion`);return l1(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){let t=this.commandManager.getTerm(`motion`);!l1(t)||typeof t.setReferenceVisible!=`function`||t.setReferenceVisible(e)}async buildScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{let t=this.scene.getObjectByName(`MuJoCo Root`);t&&this.scene.remove(t);let n={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await rP(this.mujoco,e,n),!this.mjModel||!this.mjData)throw Error(`Failed to load MuJoCo model.`);this.mujocoRoot=this.scene.getObjectByName(`MuJoCo Root`),this.mujoco.mj_forward(this.mjModel,this.mjData),UN(this.mujoco,this.mjData,this.lights),WN(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001;let r=this.policyCtrlDt??.02;this.decimation=Math.max(1,Math.round(r/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new EB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async buildSceneFromMjz(e){try{let t=await cP(this.mujoco,e);await this.buildScene(t)}catch(e){throw this.loadingScene=null,d1(e)?new u1:e}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&=(Cz(this.splatMesh,this.scene),null),this.colliderMesh&&=(TB(this.colliderMesh,this.scene),null),e&&await this.applySplat(e)}async applySplat(e){this.currentSplatTransform=e.transform??{},this.splatMesh=Sz(e.data,this.currentSplatTransform,this.scene),e.collider&&(this.colliderMesh=await wB(e.collider,this.scene))}calibrateSplat(e){this.currentSplatTransform=e,this.splatMesh&&xz(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}get commands(){return this.commandManager}play(){this.running=!0,this.startLoop()}pause(){this.stop()}get isRunning(){return this.running}getCameraView(){let e=this.camera.position.clone().sub(this.controls.target),t=e.length(),n=VN(e),r=VN(this.controls.target.clone()),i=180/Math.PI,a=t>1e-9?Math.asin(-n.z/t)*i:0,o=Math.atan2(n.y,n.x)*i;return{lookat:[r.x,r.y,r.z],distance:t,azimuth:o,elevation:a,fovy:this.camera.fov}}setCameraView(e){let t=this.getCameraView(),n=e.lookat??t.lookat,r=e.distance??t.distance,i=e.elevation??t.elevation,a=e.azimuth??t.azimuth;this.camera.fov=e.fovy??t.fovy,this.camera.updateProjectionMatrix(),this.camera.position.copy(OB(n,r,i,a)),this.controls.target.copy(BN(n)),this.controls.update()}frameCamera(){if(!this.mujocoRoot)return;let e=new Cb().setFromObject(this.mujocoRoot);if(e.isEmpty())return;let t=e.getCenter(new Y),n=e.getSize(new Y).length(),r=this.camera.fov*Math.PI/180,i=n/(2*Math.tan(r/2)),a=this.getCameraView(),o=VN(t);this.setCameraView({lookat:[o.x,o.y,o.z],distance:i>0?i:a.distance})}async stop(){this.running=!1;let e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){let e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build(),t=this.policyRunner.collectObservationsByKey(e);await this.runOnnxInference(t)}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){let e=this.policyStateBuilder.build();if(this.terminationManager.evaluate(e).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}this.commandManager.update(t),this.commandManager.updateDebugVisuals()}let n=(performance.now()-e)/1e3,r=Math.max(0,t-n);r>0&&await new Promise(e=>setTimeout(e,r*1e3))}this.loopPromise=null}async loadPolicyConfig(e){if(this.policyPlugins=e?.plugins??{},this.policyRunner=null,this.policyStateBuilder=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.commandManager.clear(),e){if(!this.mjModel||!this.mjData){console.warn(`Policy config loaded before MuJoCo model is ready.`);return}this.resetSimulationState();try{let t=e.config;if(Array.isArray(t.motions)){let n=new Map(e.motions.map(e=>[e.name,e.data]));t.motions=t.motions.map(e=>({...e,data:n.get(e.name)}))}if(t.commands?.motion&&Array.isArray(t.motions)&&(t.commands.motion={...t.commands.motion,motions:t.motions}),this.initialQpos=Array.isArray(t.initial_qpos)?t.initial_qpos:null,this.initialQvel=Array.isArray(t.initial_qvel)?t.initial_qvel:null,this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),t.commands&&typeof t.commands==`object`){this.initializeCommandsFromConfig(t.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),this.commandManager.resetTerms();let e=this.commandManager.getTerm(`motion`);l1(e)&&(await e.setSelectedMotion(t.motions?.find(e=>e.default)?.name??t.motions?.[0]?.name??null),e.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!t.policy_num_actions&&(!t.policy_joint_names||t.policy_joint_names.length===0))throw Error(`Policy config missing policy_joint_names.`);let n=new q$(t,{policyModules:{tracking:Q$,locomotion:e1},observations:{...jB,...this.policyPlugins.observations},motions:e.motions});await n.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,commandManager:this.commandManager}),await n.preloadAll(),this.policyRunner=n,this.policyStateBuilder=new Y$(this.mujoco,this.mjModel,this.mjData,n.getPolicyJointNames());let r=this.policyStateBuilder.build();this.policyRunner.reset(r),this.policyControl=this.buildPolicyControl(t,n,this.policyStateBuilder);{let e=t.observations,n=[];if(Array.isArray(e))n.push(...e);else if(e&&typeof e==`object`)for(let t of Object.values(e))Array.isArray(t)&&n.push(...t);for(let e of n)if(!(!e||this.timestep<=0)&&typeof e.fps==`number`&&e.fps>0){this.policyCtrlDt=1/e.fps;let t=Math.max(1,Math.round(this.policyCtrlDt/this.timestep));t!==this.decimation&&(console.log(`[PolicyRunner] Decimation updated: ${this.decimation} → ${t} (fps=${e.fps}, sim_dt=${this.timestep})`),this.decimation=t);break}}t.terminations&&Object.keys(t.terminations).length>0&&(this.terminationManager=new AV(t.terminations,{...jV,...this.policyPlugins.terminations},n),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`));let i=new J$(e.onnx,t.onnx?.meta);await i.init(),this.onnxModule=i,this.onnxInputDict=i.initInput(),console.log(`[PolicyRunner] config loaded`,{obsSize:n.getObservationSize(),obsLayout:n.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(e){console.warn(`Failed to load policy config:`,e)}}}buildPolicyControl(e,t,n){let r=t.getPolicyJointNames(),i=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(n,a,o,s,c,l,u,d)=>{let f=o.qposAdr.length,p=o.actionIndices.map(e=>r[e]),m=this.normalizeControlArray(s,f,1,p),h=this.normalizeControlArray(c,f,0,p),g=d?t.getDefaultJointPos():new Float32Array(r.length),_=new Float32Array(f);for(let e=0;e<f;e++)_[e]=g[o.actionIndices[e]];let v=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(r.length),y=new Float32Array(f);for(let e=0;e<f;e++)y[e]=v[o.actionIndices[e]]??0;let b=this.normalizeControlArray(l,f,0,p),x=this.normalizeControlArray(u,f,0,p),S=o.ctrlAdr.map(e=>e<0||!this.mjModel?!1:this.mjModel.actuator_biastype[e]===i),C=S.some(Boolean),w=S.some(e=>!e);return C&&w&&console.warn(`[PolicyRunner] Action term "${n}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${n}" (${a}): ${f} joint(s), mode: ${C?`position (ctrl=target_pos)`:`motor (ctrl=torque, external PD)`}`),{controlType:a,ctrlAdr:o.ctrlAdr,qposAdr:o.qposAdr,qvelAdr:o.qvelAdr,actionIndices:o.actionIndices,actionScale:m,actionOffset:h,defaultJointPos:_,encoderBias:y,positionActuator:S,kp:b,kd:x,muscleNormalize:!1}},o=e.actions;if(!o||Object.keys(o).length===0){let t=e.control_type??`joint_position`;if(t!==`joint_position`&&t!==`torque`)return console.warn(`[PolicyRunner] Unsupported control_type: ${t}`),null;let r=n.getControlMapping();return r?[a(`legacy`,t,{...r,actionIndices:Array.from({length:r.qposAdr.length},(e,t)=>t)},e.action_scale,void 0,e.stiffness,e.damping,!0)]:(console.warn(`[PolicyRunner] Failed to build control mapping.`),null)}let s=[];for(let[e,t]of Object.entries(o)){let i=t.type??`joint_position`;if(i!==`joint_position`&&i!==`torque`&&i!==`muscle_activation`){console.warn(`[PolicyRunner] Action term "${e}": unsupported type "${i}", skipping.`);continue}let o=t.actuator_names??[`.*`];if(i===`muscle_activation`){let r=n.getCtrlMappingByActuatorNames(o);if(!r){console.warn(`[PolicyRunner] Action term "${e}": no actuators matched patterns [${o.join(`, `)}], skipping.`);continue}let a=r.ctrlAdr.length,c=this.normalizeControlArray(t.scale,a,1),l=this.normalizeControlArray(t.offset,a,0),u=t.normalize??!0;console.log(`[PolicyRunner] Action term "${e}" (muscle_activation): ${a} actuator(s), normalize=${u}`),s.push({controlType:i,ctrlAdr:r.ctrlAdr,qposAdr:[],qvelAdr:[],actionIndices:r.actionIndices,actionScale:c,actionOffset:l,defaultJointPos:new Float32Array(a),encoderBias:new Float32Array(a),positionActuator:Array(a).fill(!1),kp:new Float32Array(a),kd:new Float32Array(a),muscleNormalize:u});continue}let c=o.length===1&&o[0]===`.*`,l;if(c){let t=n.getControlMapping();if(!t){console.warn(`[PolicyRunner] Action term "${e}": failed to build control mapping, skipping.`);continue}l={...t,actionIndices:Array.from({length:t.qposAdr.length},(e,t)=>t)}}else if(l=n.getControlMappingFor(o,r),!l){console.warn(`[PolicyRunner] Action term "${e}": no joints matched patterns [${o.join(`, `)}], skipping.`);continue}let u=t.use_default_offset===void 0?i===`joint_position`:t.use_default_offset;s.push(a(e,i,l,t.scale,t.offset,t.stiffness,t.damping,u))}return s.length===0?(console.warn(`[PolicyRunner] No valid action terms found in config.actions.`),null):s}normalizeControlArray(e,t,n,r){let i=new Float32Array(t);if(i.fill(n),typeof e==`number`)return i.fill(e),i;if(Array.isArray(e)){for(let r=0;r<t;r++)i[r]=typeof e[r]==`number`?e[r]:n;return i}if(typeof e==`object`&&e&&r){for(let[n,a]of Object.entries(e)){let e=r.indexOf(n);e>=0&&e<t?i[e]=a:console.warn(`[PolicyRunner] Joint name "${n}" not found in policy_joint_names; skipping.`)}return i}return i}resetSimulationState(){if(!(!this.mjModel||!this.mjData)){if(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.initialQpos){let e=this.mjData.qpos;for(let t=0;t<Math.min(this.initialQpos.length,this.mjModel.nq);t++)e[t]=this.initialQpos[t]}if(this.initialQvel){let e=this.mjData.qvel;for(let t=0;t<Math.min(this.initialQvel.length,this.mjModel.nv);t++)e[t]=this.initialQvel[t]}this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),this.commandManager.resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState()}}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;let e=this.mjData.ctrl;e.fill(0);let t=this.policyRunner?.getLastActions()??new Float32Array;for(let n of this.policyControl){let{controlType:r,ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s,actionScale:c,actionOffset:l,defaultJointPos:u,encoderBias:d,positionActuator:f,kp:p,kd:m,muscleNormalize:h}=n,g=i.length;if(r===`joint_position`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let h=t[s[n]]??0,g=u[n]+l[n]+c[n]*h-d[n];if(f[n])e[r]=g;else{let t=this.mjData.qpos[a[n]],i=this.mjData.qvel[o[n]];e[r]=p[n]*(g-t)+m[n]*(0-i)}}else if(r===`torque`)for(let n=0;n<g;n++){let r=i[n];r>=0&&(e[r]=c[n]*(t[s[n]]??0))}else if(r===`muscle_activation`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let a=(t[s[n]]??0)*c[n]+l[n];h?e[r]=1/(1+Math.exp(-5*(a-.5))):e[r]=a<0?0:a>1?1:a}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||=this.onnxModule.initInput();let t={...this.onnxInputDict};this.onnxModule.inKeys.includes(`time_step`)&&(t.time_step=new bH(`float32`,new Float32Array([this.onnxTimeStep]),[1,1]));for(let[n,r]of Object.entries(e))t[n]=new bH(`float32`,r,[1,r.length]);for(let e of this.onnxModule.inKeys)if(!t[e]){console.warn(`[PolicyRunner] Missing ONNX input:`,{key:e,available:Object.keys(t)});return}let[n,r]=await this.onnxModule.runInference(t);Object.keys(r).length>0&&(this.onnxInputDict={...this.onnxInputDict,...r}),this.onnxModule.inKeys.includes(`time_step`)&&(this.onnxTimeStep+=1);let i=this.onnxModule.outKeys[0],a=n.action??(i?n[i]:null)??n.policy??null;if(!a)return;let o=a.data,s=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&s.length!==c){console.warn(`[PolicyRunner] Action size mismatch:`,{expected:c,got:s.length});return}this.policyRunner.setLastActions(s)}catch(e){console.warn(`[PolicyRunner] ONNX inference failed:`,e)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let e=0;e<this.mjData.xfrc_applied.length;e++)this.mjData.xfrc_applied[e]=0;let e=this.dragStateManager.physicsObject;if(!e||!(`bodyID`in e)||typeof e.bodyID!=`number`||e.bodyID<=0)return;let t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let e=0;e<this.mjModel.nbody;e++)this.bodies[e]&&(aP(this.mjData.xpos,e,this.bodies[e].position),oP(this.mjData.xquat,e,this.bodies[e].quaternion),this.bodies[e].updateWorldMatrix(!0,!1));this.dragStateManager.update();let n=VN(this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale)),r=VN(this.dragStateManager.worldHit.clone()),i=new Y(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),a=new Y(r.x-i.x,r.y-i.y,r.z-i.z),o=new Y(n.x,n.y,n.z),s=new Y().crossVectors(a,o),c=t*6;this.mjData.xfrc_applied[c+0]=n.x,this.mjData.xfrc_applied[c+1]=n.y,this.mjData.xfrc_applied[c+2]=n.z,this.mjData.xfrc_applied[c+3]=s.x,this.mjData.xfrc_applied[c+4]=s.y,this.mjData.xfrc_applied[c+5]=s.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new Y,quaternion:new Zy});let e=this.lastSimState.bodies.get(t);aP(this.mjData.xpos,t,e.position),oP(this.mjData.xquat,t,e.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&ZN(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=kB(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){let t=new Set;for(let n=1;n<e.nbody;n++){let r=n;for(;r>0;){if(e.body_jntnum[r]>0){t.add(n);break}r=e.body_parentid[r]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;let n=this.bodies[t];n&&(aP(this.mjData.xpos,t,n.position),oP(this.mjData.xquat,t,n.quaternion))}}async captureThumbnail(e={}){let{maxDim:t=1280,quality:n=.85}=e,r=this.renderer.domElement;this.renderer.render(this.scene,this.camera);let i=r.width,a=r.height;if(!i||!a)throw Error(`mjswan: canvas has zero size; nothing to capture.`);let o=Math.min(1,t/Math.max(i,a)),s=Math.max(1,Math.round(i*o)),c=Math.max(1,Math.round(a*o)),l=document.createElement(`canvas`);l.width=s,l.height=c;let u=l.getContext(`2d`);if(!u)throw Error(`mjswan: failed to get a 2D context for thumbnail capture.`);return u.drawImage(r,0,0,s,c),await new Promise((e,t)=>{l.toBlob(n=>n?e(n):t(Error(`mjswan: toBlob returned null.`)),`image/jpeg`,n)})}async dispose(){await this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.onnxModule&&=(this.onnxModule.dispose(),null),this.onnxInputDict=null,this.onnxInferencing=!1,this.splatMesh&&=(Cz(this.splatMesh,this.scene),null),this.colliderMesh&&=(TB(this.colliderMesh,this.scene),null),this.dragStateManager&&=(this.dragStateManager.dispose(),null),this.mjData=null,this.mjModel=null,window.removeEventListener(`resize`,this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear(),this.commandManager.dispose()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{`geometry`in e&&e.geometry&&e.geometry.dispose(),`material`in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){let t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){let e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}};function p1(e){let t=e.config,n={id:e.id,group:e.groupName,type:t.type,label:t.label};return t.type===`slider`?{...n,min:t.min,max:t.max,step:t.step,enabledWhen:t.enabled_when}:n}async function m1(e){return{config:e.config,onnx:await UB(e.onnx),motions:(e.motions??[]).map(e=>({name:e.name,data:e.data,default:e.default})),plugins:e.plugins}}async function h1(e){return{data:await UB(e.data),collider:e.collider?await UB(e.collider):null,transform:e.transform}}var g1=class{constructor(e){this.phase=`paused`,this.loading=!1,this.loadingMessage=null,this.error=null,this.listeners=new Set,this.onCommandEvent=()=>this.refresh(),this.runtime=e,this.state=this.buildState(),this.runtime.commands.addEventListener(this.onCommandEvent),this.camera={set:e=>this.runtime.setCameraView(e),get:()=>this.runtime.getCameraView(),frame:()=>this.runtime.frameCamera()},this.commands={set:(e,t)=>this.runtime.commands.setValue(e,t),trigger:e=>this.runtime.commands.triggerButton(e)}}buildState(){let e=this.runtime.commands;return{phase:this.phase,loading:this.loading,loadingMessage:this.loadingMessage,error:this.error,commands:e.getCommands().map(p1),commandValues:e.getValues()}}refresh(){this.state=this.buildState();for(let e of this.listeners)try{e(this.state)}catch(e){console.warn(`[mjswan] subscribe listener error:`,e)}}async loadScene(e){this.loading=!0,this.loadingMessage=`Loading scene…`,this.error=null,this.refresh();try{let t={model:await UB(e.model),policy:e.policy?await m1(e.policy):null,splat:e.splat?await h1(e.splat):null,viewer:e.viewer??null,events:e.events??null,terrainData:e.terrainData??null,plugins:e.plugins};await this.runtime.loadEnvironment(t),this.phase=this.runtime.isRunning?`running`:`paused`}catch(e){throw this.error=e instanceof Error?e:Error(String(e)),e}finally{this.loading=!1,this.loadingMessage=null,this.refresh()}}async setPolicy(e){await this.runtime.loadPolicyConfig(e?await m1(e):null),this.refresh()}async setSplat(e){await this.runtime.setSplat(e?await h1(e):null)}setMotion(e){return this.runtime.setSelectedMotion(e)}setReferenceVisible(e){this.runtime.setReferenceVisible(e)}calibrateSplat(e){this.runtime.calibrateSplat(e)}play(){this.runtime.play(),this.phase=`running`,this.refresh()}pause(){this.runtime.pause(),this.phase=`paused`,this.refresh()}reset(){this.runtime.resetSimulation()}getState(){return this.state}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}captureThumbnail(e){return this.runtime.captureThumbnail(e)}dispose(){this.runtime.commands.removeEventListener(this.onCommandEvent),this.listeners.clear(),this.runtime.dispose()}};async function _1(e,t={}){return new g1(new f1(await(t.multithreaded?await i(()=>import(`./mujoco-Bacjb_-g.js`),__vite__mapDeps([0,1,2])):await i(()=>import(`./mujoco-CKOf6FiF.js`),__vite__mapDeps([3,1,2]))).default(),e))}globalThis.__mjswanThree=lA;function v1(e){return e.toLowerCase().replace(/ /g,`_`).replace(/-/g,`_`)}function y1(e){return e.id?e.id:`main`}function b1(e,t){let n=t.path?t.path:`scene/${v1(t.name)}/scene.mjz`;return`${y1(e)}/assets/${n}`.replace(/\/+/g,`/`)}function x1(e,t){return`${y1(e)}/assets/${t}`.replace(/\/+/g,`/`)}function S1(e,t){let n=e.lastIndexOf(`/`);return`${n>=0?e.slice(0,n+1):``}${t}`.replace(/\/+/g,`/`)}function C1(e){return async()=>{let t=await fetch(e);if(!t.ok)throw Error(`mjswan/manifest: failed to fetch ${e}: ${t.status}`);return t.arrayBuffer()}}async function w1(e){let t=typeof e==`function`?await e():e;return JSON.parse(new TextDecoder().decode(t))}function T1(e){return{scale:e.scale,xOffset:e.xOffset,yOffset:e.yOffset,zOffset:e.zOffset,roll:e.roll,pitch:e.pitch,yaw:e.yaw}}function E1(e,t,n){return{data:t.path?n(x1(e,t.path)):C1(t.url),collider:t.colliderUrl?/^[a-z]+:\/\//i.test(t.colliderUrl)?C1(t.colliderUrl):n(x1(e,t.colliderUrl)):void 0,transform:T1(t)}}async function D1(e,t,n){if(!t.config)throw Error(`mjswan/manifest: policy "${t.name}" has no config path.`);let r=x1(e,t.config),i=await w1(n(r)),a=i.onnx?.path;if(!a)throw Error(`mjswan/manifest: policy "${t.name}" config missing onnx.path.`);return{config:i,onnx:n(S1(r,a)),motions:Array.isArray(i.motions)?i.motions.map(e=>({name:e.name,data:n(S1(r,e.path)),default:e.default})):[]}}function O1(e,t,n){let r=t.policies.map(t=>({name:t.name,default:t.default??!1,motions:(t.motions??[]).map(e=>({name:e.name,default:e.default??!1})),build:()=>D1(e,t,n)})),i=(t.splats??[]).map(t=>({name:t.name,control:t.control??!1,transform:T1(t),build:async()=>E1(e,t,n)}));return{name:t.name,camera:t.camera,splatSection:t.splatSection??!1,policies:r,splats:i,buildScene:async r=>{let i=r?.policy,a=i==null?t.policies.find(e=>e.default)??t.policies[0]:t.policies.find(e=>e.name===i),o=r?.splat,s=o==null?void 0:t.splats?.find(e=>e.name===o);return{model:n(b1(e,t)),policy:a?await D1(e,a,n):null,splat:s?E1(e,s,n):null,viewer:t.camera,events:t.events,terrainData:t.terrainData}}}}function k1(e,t){let n=typeof e==`string`?JSON.parse(e):e;if(!n.projects?.length)throw Error(`mjswan/manifest: config.json has no projects.`);return{projects:[...n.projects.filter(e=>e.id===null),...n.projects.filter(e=>e.id!==null)].map(e=>({name:e.name,id:e.id,scenes:e.scenes.map(n=>O1(e,n,t))})),pluginsPath:n.plugins}}var A1=`panel`,j1=`ref`;function M1(e){return new URLSearchParams(window.location.search).get(e)!==`0`}function N1(e){return t=>async()=>{let n=`${e}${t}`.replace(/([^:])\/{2,}/g,`$1/`),r=await fetch(n);if(!r.ok)throw Error(`Failed to fetch ${n}: ${r.status}`);return r.arrayBuffer()}}async function P1(e){let t=new URLSearchParams(window.location.search).get(`config`),n=t?new URL(t,window.location.href).toString():`${e}assets/config.json`.replace(/([^:])\/{2,}/g,`$1/`),r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`Failed to fetch ${n}: ${r.status}`);return k1(await r.text(),N1(e))}function F1(e,t,n){if(!t)return n;let r=t.trim().toLowerCase();return e.find(e=>e.name.toLowerCase()===r)??e.find(e=>v1(e.name)===r)??n}function I1(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[a,o]=(0,b.useState)(null),[s,c]=(0,b.useState)(null),[l,u]=(0,b.useState)(null),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),[h,g]=(0,b.useState)(()=>M1(j1)),[_,v]=(0,b.useState)(()=>M1(A1)),[y,x]=(0,b.useState)(null),S=(0,b.useRef)(null),C=(0,b.useRef)(null),w=(0,b.useRef)(null),{showLoading:T,hideLoading:E,setLoadingMessage:D}=Zg(),O=(0,b.useCallback)(e=>{let t=w.current;return t?(e.plugins=t,e.policy&&(e.policy.plugins=t),e):e},[]);(0,b.useEffect)(()=>{T(`Loading…`),P1(`/`).then(async e=>{if(e.pluginsPath){let t=`/${e.pluginsPath}`.replace(/([^:])\/{2,}/g,`$1/`);w.current=await i(()=>import(t),[])}let n=new URLSearchParams(window.location.search),r=F1(e.projects,n.get(`project`),e.projects[0]),a=F1(r?.scenes??[],n.get(`scene`),r?.scenes[0]),s=a?F1(a.policies,n.get(`policy`),a.policies.find(e=>e.default)??a.policies[0]):void 0,l=s?.motions.find(e=>e.default)??s?.motions[0];t(e),o(r?.name??null),c(a?.name??null),u(s?.name??null),f(l?.name??null),m(a?.splats[0]?.name??null)}).catch(e=>{r(e instanceof Error?e.message:String(e)),E(),n_()})},[]);let k=(0,b.useMemo)(()=>e?.projects.find(e=>e.name===a)??e?.projects[0]??null,[e,a]),A=(0,b.useMemo)(()=>k?.scenes.find(e=>e.name===s)??null,[k,s]);(0,b.useEffect)(()=>{let t=S.current;if(!e||!A||!t)return;let n=!1;return(async()=>{T(`Loading MuJoCo…`);let e=await _1(t,{multithreaded:!1});if(n){e.dispose();return}C.current=e,e.subscribe(x);try{D(`Loading scene…`);let t=await A.buildScene({policy:l,splat:p});await e.loadScene(O(t)),d&&await e.setMotion(d),e.setReferenceVisible(h),E(),t_()}catch(e){r(e instanceof Error?e.message:String(e)),E(),n_()}})(),()=>{n=!0,C.current?.dispose(),C.current=null}},[e]),(0,b.useEffect)(()=>{y&&(y.loading?T(y.loadingMessage??`Loading…`):y.error||E(),y.error&&(r(y.error.message),E(),n_()))},[y,T,E]);let j=(0,b.useCallback)(t=>{let n=new URLSearchParams(window.location.search),r=(e,t,r)=>t!=null&&r?n.set(e,t):n.delete(e);r(`project`,t.project??a,(e?.projects.length??0)>1),r(`scene`,t.scene??s,!0),r(`policy`,t.policy??l,!0),n.delete(A1),(t.panel??_)||n.set(A1,`0`),n.delete(j1),(t.ref??h)||n.set(j1,`0`);let i=n.toString();window.history.replaceState({},``,`${window.location.pathname}${i?`?${i}`:``}${window.location.hash}`)},[a,s,l,_,h,e]),M=(0,b.useCallback)(async e=>{let t=C.current;if(!t)return;let n=e.policies.find(e=>e.default)??e.policies[0],r=n?.motions.find(e=>e.default)??n?.motions[0],i=e.splats[0]?.name??null;c(e.name),u(n?.name??null),f(r?.name??null),m(i),j({scene:e.name,policy:n?.name??null}),T(`Loading scene "${e.name}"…`);try{await t.loadScene(O(await e.buildScene({policy:n?.name,splat:i}))),r&&await t.setMotion(r.name),t.setReferenceVisible(h)}catch(e){console.error(`Failed to load scene:`,e)}finally{E()}},[h,j,T,E,O]),N=(0,b.useCallback)(async e=>{let t=k?.scenes.find(t=>t.name===e);t&&await M(t)},[k,M]),P=(0,b.useCallback)(async t=>{let n=e?.projects.find(e=>e.name===t);n&&(o(n.name),j({project:n.name}),n.scenes[0]&&await M(n.scenes[0]))},[e,j,M]),F=(0,b.useCallback)(async e=>{let t=C.current,n=A?.policies.find(t=>t.name===e)??null;u(e);let r=n?.motions.find(e=>e.default)??n?.motions[0];if(f(r?.name??null),j({policy:e}),t){T(e?`Loading policy "${e}"…`:`Clearing policy…`);try{let e=n?await n.build():null;e&&w.current&&(e.plugins=w.current),await t.setPolicy(e),r&&await t.setMotion(r.name),t.setReferenceVisible(h)}catch(e){console.error(`Failed to load policy:`,e)}finally{E()}}},[A,h,j,T,E]),I=(0,b.useCallback)(async e=>{let t=C.current,n=d;if(f(e),t){T(e===null?`Clearing motion…`:`Loading motion "${e}"…`);try{!await t.setMotion(e)&&e!==null&&f(n)}catch(e){console.error(`Failed to load motion:`,e)}finally{E()}}},[d,T,E]),L=(0,b.useCallback)(async e=>{let t=C.current,n=e===null?null:A?.splats.find(t=>t.name===e)??null;if(m(e),!(!t||e!==null&&!n)){T(e===null?`Removing splat…`:`Loading splat "${e}"…`);try{await t.setSplat(n?await n.build():null)}catch(e){console.error(`Failed to load splat:`,e)}finally{E()}}},[A,T,E]),R=(0,b.useCallback)(e=>{g(e),C.current?.setReferenceVisible(e),j({ref:e})},[j]),z=(0,b.useCallback)(e=>{v(e),j({panel:e})},[j]),B=(0,b.useCallback)(e=>e.map(e=>({value:e.name,label:e.name})),[]);return n?(0,G.jsx)(fr,{theme:Yg,defaultColorScheme:`auto`,children:(0,G.jsx)(`div`,{className:`app`,children:(0,G.jsxs)(`div`,{className:`hud hud-error`,children:[(0,G.jsx)(`h1`,{className:`hud-title`,children:`mjswan`}),(0,G.jsx)(`p`,{className:`hud-message`,children:n})]})})}):(0,G.jsx)(fr,{theme:Yg,defaultColorScheme:`auto`,children:(0,G.jsxs)(`div`,{className:`app`,children:[(0,G.jsx)($g,{}),e&&A&&(0,G.jsx)(Gg,{visible:_,onVisibleChange:z,projects:B(e.projects),projectValue:k?.name??null,projectLabel:k?.name??``,onProjectChange:P,scenes:B(k?.scenes??[]),sceneValue:s,onSceneChange:N,splats:B(A.splats),splatSection:A.splatSection,splatValue:p,onSplatChange:L,splatConfig:(()=>{let e=A.splats.find(e=>e.name===p);return e?{name:e.name,control:e.control,...e.transform}:null})(),onCalibrateSplat:(e,t,n,r,i,a,o)=>C.current?.calibrateSplat({scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o}),policies:B(A.policies),policyValue:l,onPolicyChange:F,motions:B(A.policies.find(e=>e.name===l)?.motions??[]),motionValue:d,onMotionChange:I,showReferenceMotion:h,onShowReferenceMotionChange:R,commandsEnabled:!!l,commands:y?.commands?[...y.commands]:[],commandValues:y?.commandValues??{},onCommandChange:(e,t)=>C.current?.commands.set(e,t),onReset:()=>C.current?.reset()}),(0,G.jsx)(`div`,{ref:S,className:`viewer`})]})})}function L1(){return(0,G.jsx)(Qg,{children:(0,G.jsx)(I1,{})})}var R1=document.getElementById(`root`);R1&&(0,wg.createRoot)(R1).render((0,G.jsx)(b.StrictMode,{children:(0,G.jsx)(L1,{})}));
15597
+ ${a}`,s=n.createShaderModule({code:o,label:e.name});QU(`verbose`,()=>`[WebGPU] ${e.name} shader code: ${o}`);let c=n.createComputePipeline({compute:{module:s,entryPoint:`main`},layout:`auto`,label:e.name});return DH(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e==`number`?e:e.x,n=typeof e==`number`?1:e.y||1,r=typeof e==`number`?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw Error(`Total dispatch size exceeds WebGPU maximum.`);return[o,o,o]}else return[o,o,1]}}}),qQ={};zV(qQ,{WebGpuBackend:()=>ZQ});var JQ,YQ,XQ,ZQ,QQ=Z(()=>{zH(),UU(),$U(),cW(),FW(),WQ(),KQ(),JQ=(e,t)=>{if(t.length!==e.length)throw Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r<e.length;++r){let i=e[r].dataType;switch(t[r]){case`none`:n.push(``);break;case`type`:n.push(`${i}`);break;case`rank`:{let t=e[r].dims.length;n.push(`${i};${t}`);break}case`dims`:{let t=e[r].dims.join(`,`);n.push(`${i};${t}`);break}default:throw Error(`unsupported input dependency: ${t[r]}`)}}return n.join(`|`)},YQ=(e,t,n)=>{let r=e.name;return e.shaderCache?.hint&&(r+=`[`+e.shaderCache.hint+`]`),r+=`:`+n+`:${JQ(t,e.shaderCache?.inputDependencies??Array(t.length).fill(`dims`))}`,r},XQ=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},ZQ=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus=`default`,this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw Error(`currentKernelCustomData(): currentKernelId is null. (should not happen)`);let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i(`chromium-experimental-timestamp-query-inside-passes`)||i(`timestamp-query`),i(`shader-f16`),i(`subgroups`),this.device=await t.requestDevice(r),this.adapterInfo=new XQ(t.info||await t.requestAdapterInfo()),this.gpuDataManager=PW(this),this.programManager=new GQ(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,XU(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<`u`&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||=this.device.createCommandEncoder(),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType===`at-passes`&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&=(this.computePassEncoder.end(),null)}flush(){if(!this.commandEncoder)return;EH(),this.endComputePass();let e;this.queryType!==`none`&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==`none`&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let r=n[e],i=r.kernelId,a=this.kernels.get(i),o=a.kernelType,s=a.kernelName,c=r.programName,l=r.inputTensorViews,u=r.outputTensorViews,d=t[e*2],f=t[e*2+1];typeof this.queryTimeBase>`u`&&(this.queryTimeBase=d);let p=Number(d-this.queryTimeBase),m=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(p)||!Number.isSafeInteger(m))throw RangeError(`incorrect timestamp range`);if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map(e=>({dims:e.dims,dataType:IU(e.dataType)})),outputsMetadata:u.map(e=>({dims:e.dims,dataType:IU(e.dataType)})),kernelId:i,kernelType:o,kernelName:s,programName:c,startTime:p,endTime:m});else{let e=``;l.forEach((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${IU(t.dataType)}, `});let t=``;u.forEach((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${IU(e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${s}|${c}" ${e}${t}start time: ${p} ns, execution time: ${m-p} ns`)}wH(`GPU`,`${c}::${d}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),DH()}run(e,t,n,r,i,a){EH(e.name);let o=[];for(let e=0;e<t.length;++e){let n=t[e].data;if(n===0)continue;let r=this.gpuDataManager.get(n);if(!r)throw Error(`no GPU data for input: ${n}`);o.push(r)}let{outputs:s,dispatchGroup:c,programUniforms:l}=e.getRunData(t),u=n.length===0?s.map((e,t)=>t):n;if(u.length!==s.length)throw Error(`Output size ${u.length} must be equal to ${s.length}.`);let d=[],f=[];for(let e=0;e<s.length;++e){if(!Number.isInteger(u[e])||u[e]<-3||u[e]>=a)throw Error(`Invalid output index: ${u[e]}`);if(u[e]===-3)continue;let t=u[e]===-1,n=u[e]===-2,o=t||n?i(s[e].dataType,s[e].dims):r(u[e],s[e].dataType,s[e].dims);if(d.push(o),o.data===0)continue;let c=this.gpuDataManager.get(o.data);if(!c)throw Error(`no GPU data for output: ${o.data}`);if(t&&this.temporaryData.push(c),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(c)}f.push(c)}if(o.length!==t.length||f.length!==d.length){if(f.length===0)return DH(e.name),d;throw Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let p;if(l){let e=0,t=[];l.forEach(n=>{let r=typeof n.data==`number`?[n.data]:n.data;if(r.length===0)return;let i=n.type===10?2:4,a,o;n.type===10?(o=r.length>4?16:r.length>2?8:r.length*i,a=r.length>4?16:i*r.length):(o=r.length<=2?r.length*i:16,a=16),e=Math.ceil(e/o)*o,t.push(e);let s=n.type===10?8:4;e+=r.length>4?Math.ceil(r.length/s)*a:r.length*i}),e=Math.ceil(e/16)*16;let n=new ArrayBuffer(e);l.forEach((e,r)=>{let i=t[r],a=typeof e.data==`number`?[e.data]:e.data;if(e.type===6)new Int32Array(n,i,a.length).set(a);else if(e.type===12)new Uint32Array(n,i,a.length).set(a);else if(e.type===10)new Uint16Array(n,i,a.length).set(a);else if(e.type===1)new Float32Array(n,i,a.length).set(a);else throw Error(`Unsupported uniform type: ${IU(e.type)}`)});let r=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(r.buffer,0,n,0,e),this.gpuDataManager.release(r.id),p={offset:0,size:e,buffer:r.buffer}}let m=this.programManager.normalizeDispatchGroupSize(c),h=m[1]===1&&m[2]===1,g=YQ(e,t,h),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),QU(`info`,()=>`[artifact] key: ${g}, programName: ${e.name}`)),l&&_.uniformVariablesInfo){if(l.length!==_.uniformVariablesInfo.length)throw Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${l.length} in program "${_.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,r=typeof t.data==`number`?1:t.data.length,[i,a]=_.uniformVariablesInfo[e];if(n!==i||r!==a)throw Error(`Uniform variable ${e} mismatch: expect type ${i} with size ${a}, got type ${n} with size ${r} in program "${_.programInfo.name}".`)}}if(QU(`info`,()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!==`none`||this.sessionStatus===`capturing`){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:d};this.pendingKernels.push(e),this.sessionStatus===`capturing`&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,o,f,m,p),DH(e.name),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=UQ.get(e);if(!i)throw Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,o=r.kernelEntry,s=r.attributes;if(this.currentKernelId!==null)throw Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&=(s[1]=s[0](s[1]),void 0),QU(`info`,()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(`validation`),o(t,s[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{c&&n.push(this.device.popErrorScope().then(e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[o,n]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(e=>this.gpuDataManager.unregisterExternalBuffer(e[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await MW(this,e,t);return sW(r.buffer,n)}}writeTimestamp(e){this.queryType===`inside-passes`&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType=`none`,(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>`u`?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(`chromium-experimental-timestamp-query-inside-passes`)?this.queryType=`inside-passes`:this.device.features.has(`timestamp-query`)&&(this.queryType=`at-passes`),this.queryType!==`none`&&typeof this.querySet>`u`&&(this.querySet=this.device.createQuerySet({type:`timestamp`,count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){QU(`info`,`captureBegin`),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=`capturing`}captureEnd(){QU(`info`,`captureEnd`),this.flush(),this.sessionStatus=`default`}replay(){QU(`info`,`replay`),this.sessionStatus=`replaying`;let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r<n;r++){let n=this.getComputePassEncoder(),i=e[r];this.writeTimestamp(this.pendingDispatchNumber*2),n.setPipeline(i.computePipeline),n.setBindGroup(0,i.bindGroup),n.dispatchWorkgroups(...i.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!==`none`&&this.pendingKernels.push(t[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType===`at-passes`)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=`default`}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),$Q={};zV($Q,{init:()=>n$});var e$,t$,n$,r$=Z(()=>{UU(),$U(),oW(),wW(),e$=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(this.dataType!==1)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(Q.size(t)!==Q.size(this.dims))throw Error(`Invalid new shape`);return new e(this.module,this.dataType,this.data,t)}},t$=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=r===4?`i32`:`i64`;this.opKernelContext=Number(e.getValue(r*i++,a));let o=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,`*`)),this.customDataSize=Number(e.getValue(r*i++,a));let s=[];for(let t=0;t<o;t++){let t=Number(e.getValue(r*i++,a)),n=Number(e.getValue(r*i++,`*`)),o=Number(e.getValue(r*i++,a)),c=[];for(let t=0;t<o;t++)c.push(Number(e.getValue(r*i++,a)));s.push(new e$(e,t,n,c))}this.inputs=s}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(e=>typeof e==`number`?this.inputs[e]:e)??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,(e,t,n)=>new e$(this.module,t,this.output(e,n),n),(e,t)=>{let n=LU(e,t);if(!n)throw Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new e$(this.module,e,r,t)},this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=n===4?`i32`:`i64`,i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e<t.length;e++)this.module.setValue(i+n*(e+1),t[e],r);return this.module._JsepOutput(this.opKernelContext,e,i)}catch(n){throw Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`)}finally{this.module.stackRestore(n)}}},n$=async(e,t,n,r)=>{let i=t.jsepInit;if(!i)throw Error(`Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.`);if(e===`webgpu`){let e=(QQ(),VV(qQ)).WebGpuBackend,a=new e;await a.initialize(n,r),i(`webgpu`,[a,e=>a.alloc(Number(e)),e=>a.free(e),(e,n,r,i=!1)=>{if(i)QU(`verbose`,()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(e)}, dst=${Number(n)}, size=${Number(r)}`),a.memcpy(Number(e),Number(n));else{QU(`verbose`,()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(e)}, gpuDataId=${Number(n)}, size=${Number(r)}`);let i=t.HEAPU8.subarray(Number(e>>>0),Number(e>>>0)+Number(r));a.upload(Number(n),i)}},async(e,n,r)=>{QU(`verbose`,()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${e}, dataOffset=${n}, size=${r}`),await a.download(Number(e),()=>t.HEAPU8.subarray(Number(n)>>>0,Number(n+r)>>>0))},(e,n,r)=>a.createKernel(e,Number(n),r,t.UTF8ToString(t._JsepGetNodeName(Number(n)))),e=>a.releaseKernel(e),(e,n,r,i)=>{QU(`verbose`,()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${e}, contextDataOffset=${n}`);let o=new t$(t,a,Number(n));return a.computeKernel(Number(e),o,i)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let e=new CW(n);i(`webnn`,[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i,a)=>e.ensureTensor(t,n,r,i,a),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n),(t,n)=>e.registerMLContext(t,n),!!n.trace])}}}),i$,a$,o$,s$,c$,l$,u$,d$,f$,p$,m$,h$,g$,_$=Z(()=>{zH(),DU(),PU(),UU(),xU(),TU(),GU(),i$=(e,t)=>{bU()._OrtInit(e,t)!==0&&wU(`Can't initialize onnxruntime.`)},a$=async e=>{i$(e.wasm.numThreads,zU(e.logLevel))},o$=async(e,t)=>{bU().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`);{let r=(r$(),VV($Q)).init;t===`webgpu`&&await r(`webgpu`,bU(),e,n),t===`webnn`&&await r(`webnn`,bU(),e)}},s$=new Map,c$=e=>{let t=bU(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&wU(`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)}},l$=(e,t)=>{let n=bU(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&wU(`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<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},u$=e=>{let t=bU(),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]},d$=async(e,t)=>{let n,r,i=bU();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=u$(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await NU(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(WU(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&&wU(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=c$(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=l$(a,t);e===0&&wU(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:IU(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=l$(a,n+e);r===0&&wU(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:IU(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&wU(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>HU(e))}),s$.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&&wU(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&wU(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&wU(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},f$=e=>{let t=bU(),n=s$.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&&wU(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&wU(`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&&wU(`Can't release session.`),s$.delete(e)},p$=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=bU(),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=LU(FU(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=LU(FU(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,FU(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;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,SU(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=FU(l);m=LU(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(FU(l),p,m,g,u.length,HU(f));e===0&&wU(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},m$=async(e,t,n,r,i,a)=>{let o=bU(),s=o.PTR_SIZE,c=s$.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]=EU(a),OH(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await p$(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await p$(i[t],b,x,e,d[r[t]],h+r[t],p);kH(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(w+e*s,y[e],`*`),o.setValue(T+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(E+e*s,b[e],`*`),o.setValue(D+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);OH(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&wU(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&wU(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&wU(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}kH(`wasm bindInputsOutputs`),s$.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,E,_):await o._OrtRun(l,T,w,h,D,g,E,_),c!==0&&wU(`failed to call OrtRun().`);let C=[],O=[];OH(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(E+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&wU(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&wU(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&wU(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=IU(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;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=LU(a,g);if(r===void 0||!BU(u))throw Error(`Unsupported data type: ${u}`);l=!0,C.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&wU(`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(LU(a,g)===void 0||!VU(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(RU(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&&wU(`Can't clear bound outputs.`),s$.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(O))C[e][2]=t;return kH(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),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))}},h$=e=>{let t=bU(),n=s$.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&wU(`Can't get an profile file name.`),t._OrtFree(i)},g$=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),v$,y$,b$,x$,S$,C$,w$,T$,E$,D$,O$,k$,A$,j$,M$,N$,P$,F$,I$=Z(()=>{zH(),_$(),xU(),dU(),v$=()=>!!eH.wasm.proxy&&typeof document<`u`,b$=!1,x$=!1,S$=!1,T$=new Map,E$=(e,t)=>{let n=T$.get(e);n?n.push(t):T$.set(e,[t])},D$=()=>{if(b$||!x$||S$||!y$)throw Error(`worker not ready`)},O$=e=>{switch(e.data.type){case`init-wasm`:b$=!1,e.data.err?(S$=!0,w$[1](e.data.err)):(x$=!0,w$[0]()),C$&&=(URL.revokeObjectURL(C$),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=T$.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},k$=async()=>{if(!x$){if(b$)throw Error(`multiple calls to 'initWasm()' detected.`);if(S$)throw Error(`previous call to 'initWasm()' failed.`);if(b$=!0,v$())return new Promise((e,t)=>{y$?.terminate(),cU().then(([n,r])=>{try{y$=r,y$.onerror=e=>t(e),y$.onmessage=O$,w$=[e,t];let i={type:`init-wasm`,in:eH};!i.in.wasm.wasmPaths&&(n||QH)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm`,``+import.meta.url).href}),y$.postMessage(i),C$=n}catch(e){t(e)}},t)});try{await yU(eH.wasm),await a$(eH),x$=!0}catch(e){throw S$=!0,e}finally{b$=!1}}},A$=async e=>{if(v$())return D$(),new Promise((t,n)=>{E$(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:eH}};y$.postMessage(r)});await o$(eH,e)},j$=async e=>v$()?(D$(),new Promise((t,n)=>{E$(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};y$.postMessage(r,[e.buffer])})):u$(e),M$=async(e,t)=>{if(v$()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return D$(),new Promise((n,r)=>{E$(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),y$.postMessage(i,a)})}else return d$(e,t)},N$=async e=>{if(v$())return D$(),new Promise((t,n)=>{E$(`release`,[t,n]);let r={type:`release`,in:e};y$.postMessage(r)});f$(e)},P$=async(e,t,n,r,i,a)=>{if(v$()){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 D$(),new Promise((i,o)=>{E$(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};y$.postMessage(c,g$(s))})}else return m$(e,t,n,r,i,a)},F$=async e=>{if(v$())return D$(),new Promise((t,n)=>{E$(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};y$.postMessage(r)});h$(e)}}),L$,R$,z$,B$=Z(()=>{zH(),I$(),UU(),BH(),GU(),L$=(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()}`)}},R$=e=>{switch(e[3]){case`cpu`:return new SH(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!BU(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return SH.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!VU(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return SH.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},z$=class{async fetchModelAndCopyToWasmMemory(e){return j$(await WU(e))}async loadModel(e,t){EH();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await M$(n,t),DH()}async dispose(){return N$(this.sessionId)}async run(e,t,n){EH();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)=>L$(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?L$(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await P$(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??R$(l[e]);return DH(),u}startProfiling(){}endProfiling(){F$(this.sessionId)}}}),V$={};zV(V$,{OnnxruntimeWebAssemblyBackend:()=>U$,initializeFlags:()=>H$,wasmBackend:()=>W$});var H$,U$,W$,G$=Z(()=>{zH(),I$(),B$(),H$=()=>{(typeof eH.wasm.initTimeout!=`number`||eH.wasm.initTimeout<0)&&(eH.wasm.initTimeout=0);let e=eH.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.`),eH.wasm.simd=!1),typeof eH.wasm.proxy!=`boolean`&&(eH.wasm.proxy=!1),typeof eH.wasm.trace!=`boolean`&&(eH.wasm.trace=!1),typeof eH.wasm.numThreads!=`number`||!Number.isInteger(eH.wasm.numThreads)||eH.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)eH.wasm.numThreads=1;else{let e=typeof navigator>`u`?RV(`node:os`).cpus().length:navigator.hardwareConcurrency;eH.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},U$=class{async init(e){H$(),await k$(),await A$(e)}async createInferenceSessionHandler(e,t){let n=new z$;return await n.loadModel(e,t),n}},W$=new U$});zH(),zH(),zH();var K$=`1.24.3`;{let e=(G$(),VV(V$)).wasmBackend;WV(`webgpu`,e,5),WV(`webnn`,e,5),WV(`cpu`,e,10),WV(`wasm`,e,10)}Object.defineProperty(eH.versions,"web",{value:K$,enumerable:!0});var q$=class{constructor(e,t){this.runner=e,this.config=t}},J$=class extends q${constructor(e,t){super(e,t),this.store=new OV,this.cachedSize=null,this.graph=t.graph,this.params=t.params??{}}get size(){return this.cachedSize??this.inferSize()}reset(e){this.store.reset()}compute(e){let t=this.evaluate(e);if(this.cachedSize===null)return this.cachedSize=t.length,t;if(t.length===this.cachedSize)return t;let n=new Float32Array(this.cachedSize);return n.set(t.subarray(0,Math.min(t.length,this.cachedSize))),n}evaluate(e){let t=kV(this.graph,{runner:this.runner,state:e,params:this.params},this.store);if(t instanceof Float32Array)return t;if(typeof t==`number`)return new Float32Array([t]);if(typeof t==`boolean`)return new Float32Array([+!!t]);if(t instanceof Uint8Array){let e=new Float32Array(t.length);for(let n=0;n<t.length;n++)e[n]=t[n];return e}return new Float32Array}inferSize(){this.runner.getContext();let e={jointPos:new Float32Array(this.runner.getNumActions())};return this.compute(e),this.cachedSize??0}},Y$=class{constructor(e,t={}){this.motionCache=new Map,this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=e.policy_num_actions??this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(let t of Object.values(this.obsGroups))for(let n of t)n.reset&&n.reset(e);if(e){for(let[t,n]of Object.entries(this.historyConfig))if(n.steps>1){let r=this.buildFrame(this.obsGroups[t]??[],e),i=this.historyBuffers[t];for(let e=0;e<n.steps;e++)i.set(r,e*r.length)}}}update(e){this.policyModule?.update();for(let t of Object.values(this.obsGroups))for(let n of t)n.update&&n.update(e)}collectObservationsByKey(e){this.update(e);let t={};for(let[n,r]of Object.entries(this.obsGroups)){let i=this.historyConfig[n];if(i&&i.steps>1){let i=this.buildFrame(r,e),a=this.historyBuffers[n];for(let e=a.length-1;e>=i.length;e--)a[e]=a[e-i.length];a.set(i,0),t[n]=new Float32Array(a)}else t[n]=this.buildFrame(r,e)}return t}collectObservations(e){let t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];let n=Object.keys(t)[0];return n?t[n]:new Float32Array}async preloadAll(){let e=[];for(let t of Object.values(this.obsGroups))for(let n of t)typeof n.preload==`function`&&e.push(n.preload());await Promise.all(e)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];let e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(e=>({...e}));let e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(e=>({...e})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}getConfig(){return this.config}getMotionData(e){let t=this.motionCache.get(e);if(t)return t;let n=this.options.motions?.find(t=>t.name===e),r=n?UB(n.data):Promise.resolve(null);return this.motionCache.set(e,r),r}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){let t=this.options.policyModules??{},n=this.config.policy_module,r=n?t[n]:t.default;if(n&&!r)throw Error(`Unknown policy module: ${n}`);if(!r)return null;let i=new r(this.config);return await i.init(e),i}buildObservationGroups(){let e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;let n=t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new J$(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);return new r(this,t)};for(let[r,i]of Object.entries(t)){if(Array.isArray(i)){let e=i.map(n);this.registerGroup(r,e,i);continue}if(i&&typeof i==`object`){let t=i;if(Array.isArray(t.components)){let n=t.components.map(t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new J$(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);let i={...t,history_steps:1};return new r(this,i)}),i=Math.max(1,Math.floor(t.history_steps??1)),a=!!t.interleaved;this.registerGroup(r,n,t.components,{steps:i,interleaved:a})}}}this.obsGroups.policy?this.defaultObsKey=`policy`:this.obsGroups.observation?this.defaultObsKey=`observation`:this.obsGroups.obs_history?this.defaultObsKey=`obs_history`:this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,n,r){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((e,t)=>({name:n[t]?.name??`obs_${t}`,size:e.size}));let i=this.obsLayouts[e].reduce((e,t)=>e+t.size,0);r&&r.steps>1?(this.historyConfig[e]=r,this.historyBuffers[e]=new Float32Array(i*r.steps),this.obsSizes[e]=i*r.steps):this.obsSizes[e]=i}buildFrame(e,t){let n=e.map(e=>{let n=e.compute(t),r=n instanceof Float32Array?n:Float32Array.from(n);if(r.length!==e.size)throw Error(`Observation size mismatch: expected ${e.size}, got ${r.length}`);return r}),r=n.reduce((e,t)=>e+t.length,0),i=new Float32Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i}normalizeArray(e,t,n){let r=new Float32Array(t);for(let i=0;i<t;i++)r[i]=typeof e[i]==`number`?e[i]:n;return r}};eH.wasm.proxy=!1,eH.wasm.numThreads=1,typeof __ORT_CDN_BASE__<`u`&&(eH.wasm.wasmPaths=__ORT_CDN_BASE__);var X$=class{constructor(e,t){this.bytes=e,this.session=null;let n=t?.in_keys??[`policy`],r=t?.out_keys??[`action`];this.configuredInKeys=n.map(e=>Array.isArray(e)?e.join(`,`):e),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(e=>Array.isArray(e)?e.join(`,`):e),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}async init(){this.session=await NH.create(this.bytes,{executionProviders:[`wasm`],graphOptimizationLevel:`all`}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}initInput(){let e={};return this.isRecurrent&&(e.is_init=new SH(`bool`,[!0],[1]),e.adapt_hx=new SH(`float32`,new Float32Array(128),[1,128])),this.inKeys.includes(`time_step`)&&(e.time_step=new SH(`float32`,new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw Error(`OnnxModule not initialized.`);let t={};for(let n=0;n<this.inKeys.length;n++){let r=this.inKeys[n],i=this.session.inputNames[n];if(!i||!e[r])throw Error(`Missing ONNX input for key: ${r}`);t[i]=e[r]}let n=await this.session.run(t),r={};for(let e=0;e<this.outKeys.length;e++){let t=this.outKeys[e],i=this.session.outputNames[e];i&&n[i]&&(r[t]=n[i])}let i={};return this.isRecurrent&&r[`next,adapt_hx`]&&(i.is_init=new SH(`bool`,[!1],[1]),i.adapt_hx=r[`next,adapt_hx`]),[r,i]}dispose(){this.session?.release?.(),this.session=null}inferInputKeys(){if(!this.session)return;let e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(e=>this.configuredInKeys.includes(e)?e:e===`obs`&&this.configuredInKeys.includes(`policy`)?`policy`:e)}},Z$=class{constructor(e,t,n,r){this.mujoco=e,this.mjModel=t,this.mjData=n;let i=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(let e of r){let n=i.indexOf(e);if(n<0)throw Error(`Joint "${e}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[n]),this.qvelAdr.push(t.jnt_dofadr[n]),this.jointIndices.push(n)}this.numActions=r.length,this.ctrlAdr=this.buildCtrlAdr()}build(){let e=this.mjData.qpos,t=this.mjData.qvel,n=new Float32Array(this.numActions),r=new Float32Array(this.numActions);for(let i=0;i<this.numActions;i++)n[i]=e[this.qposAdr[i]],r[i]=t[this.qvelAdr[i]];return{jointPos:n,jointVel:r,rootPos:new Float32Array([e[0],e[1],e[2]]),rootQuat:new Float32Array([e[3],e[4],e[5],e[6]]),rootLinVel:new Float32Array([t[0],t[1],t[2]]),rootAngVel:new Float32Array([t[3],t[4],t[5]])}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;let n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[],o=[],s=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(this.ctrlAdr[e]),a.push(this.qposAdr[e]),o.push(this.qvelAdr[e]),s.push(e));return i.length===0?null:{ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s}}getCtrlMappingByActuatorNames(e){let t=this.getActuatorNames(this.mjModel),n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(e),a.push(i.length-1));return i.length>0?{ctrlAdr:i,actionIndices:a}:null}getActuatorNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.nu;i++){let a=e.name_actuatoradr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;let e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let n=0;n<this.mjModel.nu;n++){let r=this.mjModel.actuator_trntype[n];e===void 0||r===e?t.push(this.mjModel.actuator_trnid[2*n]):t.push(-1)}let n=[];for(let e of this.jointIndices){let r=t.findIndex(t=>t===e);if(r<0)return null;n.push(r)}return n}getJointNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;let s=n.decode(t.subarray(a,o));!s&&i===0&&(s=`floating_base_joint`),r.push(s)}return r}},Q$=class{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}},$$=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},e1=class extends Q${constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.tracking=new $$(n)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}},t1=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},n1=class extends Q${constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.locomotion=new t1(n)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}},r1=class{constructor(e){this.config=e}};function i1(e,t){return e+Math.random()*(t-e)}function a1(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}function o1(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}var s1=class extends r1{constructor(e){super(e),this.mutations=e.mutations??[]}onReset(e){let{mjModel:t,mjData:n}=e;if(!(!t||!n))for(let e of this.mutations)switch(e.target){case`joint_qpos`:this.applyJointOffset(t,n,e,`qpos`);break;case`joint_qvel`:this.applyJointOffset(t,n,e,`qvel`);break;case`freejoint_pos`:this.applyFreejointPos(t,n,e);break;case`freejoint_yaw`:this.applyFreejointYaw(t,n,e);break}}resolveJointIndices(e,t){let n=t.select??{};if(n.joint_ids&&n.joint_ids.length>0)return n.joint_ids.filter(t=>t>=0&&t<e.njnt);let r=a1(e);return n.joint_names&&n.joint_names.length>0?n.joint_names.map(e=>this.findJointIndex(r,e,n.entity_name)).filter(e=>e!==null):r.map((e,t)=>({name:e,idx:t})).filter(({name:t,idx:r})=>e.jnt_type[r]===0?!1:n.entity_name?t===n.entity_name||t.startsWith(`${n.entity_name}/`):!0).map(({idx:e})=>e)}findJointIndex(e,t,n){let r=e.indexOf(t);if(r>=0)return r;if(n){let r=e.indexOf(`${n}/${t}`);if(r>=0)return r}let i=e.map((e,t)=>({name:e,idx:t})).filter(({name:e})=>e===t||e.endsWith(`/${t}`));if(i.length===1)return i[0].idx;if(n){let e=i.find(({name:e})=>e===n||e.startsWith(`${n}/`));if(e)return e.idx}return null}applyJointOffset(e,t,n,r){if(n.sample.dist!==`uniform`)return;let{low:i,high:a}=n.sample;for(let o of this.resolveJointIndices(e,n)){let s=e.jnt_type[o];if(!(s!==2&&s!==3))if(r===`qpos`){let r=e.jnt_qposadr[o];if(t.qpos[r]+=i1(i,a),n.clip_to_limits&&e.jnt_limited[o]){let n=e.jnt_range[o*2],i=e.jnt_range[o*2+1];t.qpos[r]=Math.min(Math.max(t.qpos[r],n),i)}}else t.qvel[e.jnt_dofadr[o]]+=i1(i,a)}}applyFreejointPos(e,t,n){if(n.sample.dist!==`uniform_xyz`)return;let r=o1(e);if(r<0)return;let i=e.jnt_qposadr[r];t.qpos[i]+=i1(n.sample.x[0],n.sample.x[1]),t.qpos[i+1]+=i1(n.sample.y[0],n.sample.y[1]),t.qpos[i+2]+=i1(n.sample.z[0],n.sample.z[1])}applyFreejointYaw(e,t,n){if(n.sample.dist!==`uniform`)return;let r=o1(e);if(r<0)return;let i=e.jnt_qposadr[r]+3,a=i1(n.sample.low,n.sample.high),o=Math.cos(a/2),s=Math.sin(a/2),c=t.qpos[i],l=t.qpos[i+1],u=t.qpos[i+2],d=t.qpos[i+3];t.qpos[i]=o*c-s*d,t.qpos[i+1]=o*l+s*u,t.qpos[i+2]=o*u-s*l,t.qpos[i+3]=o*d+s*c}};function c1(e){return`kind`in e&&e.kind===`event`&&Array.isArray(e.mutations)}var l1=class{constructor(e,t){this.terms=[];for(let n of e){if(c1(n)){this.terms.push(new s1(n));continue}let e=t[n.name];if(!e){console.warn(`[EventManager] Unknown event type: ${n.name}`);continue}this.terms.push(new e(n))}}onReset(e){for(let t of this.terms)t.onReset(e)}get size(){return this.terms.length}},u1={};function d1(e){return typeof e==`object`&&!!e&&typeof e.setSelectedMotion==`function`}var f1=class extends Error{constructor(){super(`This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory.`),this.name=`WasmMemoryLimitError`}};function p1(e){let t=e instanceof Error?e.message:String(e);return t.includes(`MjModel loading returned null`)||t.includes(`Could not allocate memory`)||t.includes(`memory allocation failed`)||t.includes(`bad_alloc`)}var m1=class{constructor(e,t){this.render=()=>{if(this.commandManager.updateDebugVisuals(),this.mjData&&AB(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){WN(this.camera,this.lights);for(let[e,t]of this.lastSimState.bodies){let n=this.bodies[e];n&&(n.position.copy(t.position),n.quaternion.copy(t.quaternion))}UN(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&QN({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{let{width:e,height:t}=this.getSize();this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)},this.mujoco=e,this.container=t,this.commandManager=new rV,this.scenePlugins={},this.policyPlugins={};let n=`/working`;try{this.mujoco.FS.mkdir(n)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&console.warn(`Failed to create /working directory:`,e)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:`.`},n)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&e.code!==`EBUSY`&&console.warn(`Failed to mount MEMFS at /working:`,e)}let{width:r,height:i}=this.getSize();this.scene=new nC,this.scene.name=`scene`,this.camera=new GS(45,r/i,.001,1e3),this.camera.name=`PerspectiveCamera`,this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new hN({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(r,i),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=2,this.renderer.outputColorSpace=Rv,this.renderer.toneMapping=4,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported(`immersive-vr`).then(e=>{e&&(this.vrButton=zN.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new EN(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener(`resize`,this.onWindowResize),`ResizeObserver`in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:$N()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.policyCtrlDt=null,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.initialQpos=null,this.initialQvel=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.currentSplatTransform={},this.cameraState={trackBodyId:null,prevBodyPos:null}}async loadEnvironment(e){this.scenePlugins=e.plugins??{},this.terrainData=e.terrainData??null,e.events&&e.events.length>0?(this.eventManager=new l1(e.events,{...u1,...this.scenePlugins.events}),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&=(Cz(this.splatMesh,this.scene),null),this.colliderMesh&&=(TB(this.colliderMesh,this.scene),null),this.initializeCommands(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,await this.buildSceneFromMjz(e.model),e.splat&&await this.applySplat(e.splat),await this.loadPolicyConfig(e.policy??null),this.applyViewerConfig(e.viewer??null),this.running=!0,this.startLoop()}initializeCommands(){this.commandManager.clear()}initializeCommandsFromConfig(e,t){this.commandManager.initialize(e,t,this.policyPlugins.commands),console.log(`[mjswanRuntime] Commands loaded from policy config:`,Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log(`[mjswanRuntime] Simulation reset`)}async setSelectedMotion(e){let t=this.commandManager.getTerm(`motion`);if(!d1(t))return!1;let n=await t.setSelectedMotion(e);return n&&this.resetSimulation(),n}getSelectedMotionName(){let e=this.commandManager.getTerm(`motion`);return d1(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){let t=this.commandManager.getTerm(`motion`);!d1(t)||typeof t.setReferenceVisible!=`function`||t.setReferenceVisible(e)}async buildScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{let t=this.scene.getObjectByName(`MuJoCo Root`);t&&this.scene.remove(t);let n={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await rP(this.mujoco,e,n),!this.mjModel||!this.mjData)throw Error(`Failed to load MuJoCo model.`);this.mujocoRoot=this.scene.getObjectByName(`MuJoCo Root`),this.mujoco.mj_forward(this.mjModel,this.mjData),UN(this.mujoco,this.mjData,this.lights),WN(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001;let r=this.policyCtrlDt??.02;this.decimation=Math.max(1,Math.round(r/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new EB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async buildSceneFromMjz(e){try{let t=await cP(this.mujoco,e);await this.buildScene(t)}catch(e){throw this.loadingScene=null,p1(e)?new f1:e}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&=(Cz(this.splatMesh,this.scene),null),this.colliderMesh&&=(TB(this.colliderMesh,this.scene),null),e&&await this.applySplat(e)}async applySplat(e){this.currentSplatTransform=e.transform??{},this.splatMesh=Sz(e.data,this.currentSplatTransform,this.scene),e.collider&&(this.colliderMesh=await wB(e.collider,this.scene))}calibrateSplat(e){this.currentSplatTransform=e,this.splatMesh&&xz(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}get commands(){return this.commandManager}play(){this.running=!0,this.startLoop()}pause(){this.stop()}get isRunning(){return this.running}getCameraView(){let e=this.camera.position.clone().sub(this.controls.target),t=e.length(),n=VN(e),r=VN(this.controls.target.clone()),i=180/Math.PI,a=t>1e-9?Math.asin(-n.z/t)*i:0,o=Math.atan2(n.y,n.x)*i;return{lookat:[r.x,r.y,r.z],distance:t,azimuth:o,elevation:a,fovy:this.camera.fov}}setCameraView(e){let t=this.getCameraView(),n=e.lookat??t.lookat,r=e.distance??t.distance,i=e.elevation??t.elevation,a=e.azimuth??t.azimuth;this.camera.fov=e.fovy??t.fovy,this.camera.updateProjectionMatrix(),this.camera.position.copy(OB(n,r,i,a)),this.controls.target.copy(BN(n)),this.controls.update()}frameCamera(){if(!this.mujocoRoot)return;let e=new Cb().setFromObject(this.mujocoRoot);if(e.isEmpty())return;let t=e.getCenter(new Y),n=e.getSize(new Y).length(),r=this.camera.fov*Math.PI/180,i=n/(2*Math.tan(r/2)),a=this.getCameraView(),o=VN(t);this.setCameraView({lookat:[o.x,o.y,o.z],distance:i>0?i:a.distance})}async stop(){this.running=!1;let e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){let e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build(),t=this.policyRunner.collectObservationsByKey(e);await this.runOnnxInference(t)}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){let e=this.policyStateBuilder.build();if(this.terminationManager.evaluate(e).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}this.commandManager.update(t),this.commandManager.updateDebugVisuals()}let n=(performance.now()-e)/1e3,r=Math.max(0,t-n);r>0&&await new Promise(e=>setTimeout(e,r*1e3))}this.loopPromise=null}async loadPolicyConfig(e){if(this.policyPlugins=e?.plugins??{},this.policyRunner=null,this.policyStateBuilder=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.commandManager.clear(),e){if(!this.mjModel||!this.mjData){console.warn(`Policy config loaded before MuJoCo model is ready.`);return}this.resetSimulationState();try{let t=e.config;if(Array.isArray(t.motions)){let n=new Map(e.motions.map(e=>[e.name,e.data]));t.motions=t.motions.map(e=>({...e,data:n.get(e.name)}))}if(t.commands?.motion&&Array.isArray(t.motions)&&(t.commands.motion={...t.commands.motion,motions:t.motions}),this.initialQpos=Array.isArray(t.initial_qpos)?t.initial_qpos:null,this.initialQvel=Array.isArray(t.initial_qvel)?t.initial_qvel:null,this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),t.commands&&typeof t.commands==`object`){this.initializeCommandsFromConfig(t.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),this.commandManager.resetTerms();let e=this.commandManager.getTerm(`motion`);d1(e)&&(await e.setSelectedMotion(t.motions?.find(e=>e.default)?.name??t.motions?.[0]?.name??null),e.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!t.policy_num_actions&&(!t.policy_joint_names||t.policy_joint_names.length===0))throw Error(`Policy config missing policy_joint_names.`);let n=new Y$(t,{policyModules:{tracking:e1,locomotion:n1},observations:{...jB,...this.policyPlugins.observations},motions:e.motions});await n.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,commandManager:this.commandManager}),await n.preloadAll(),this.policyRunner=n,this.policyStateBuilder=new Z$(this.mujoco,this.mjModel,this.mjData,n.getPolicyJointNames());let r=this.policyStateBuilder.build();this.policyRunner.reset(r),this.policyControl=this.buildPolicyControl(t,n,this.policyStateBuilder);{let e=t.observations,n=[];if(Array.isArray(e))n.push(...e);else if(e&&typeof e==`object`)for(let t of Object.values(e))Array.isArray(t)&&n.push(...t);for(let e of n)if(!(!e||this.timestep<=0)&&typeof e.fps==`number`&&e.fps>0){this.policyCtrlDt=1/e.fps;let t=Math.max(1,Math.round(this.policyCtrlDt/this.timestep));t!==this.decimation&&(console.log(`[PolicyRunner] Decimation updated: ${this.decimation} → ${t} (fps=${e.fps}, sim_dt=${this.timestep})`),this.decimation=t);break}}t.terminations&&Object.keys(t.terminations).length>0&&(this.terminationManager=new MV(t.terminations,{...NV,...this.policyPlugins.terminations},n),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`));let i=new X$(e.onnx,t.onnx?.meta);await i.init(),this.onnxModule=i,this.onnxInputDict=i.initInput(),console.log(`[PolicyRunner] config loaded`,{obsSize:n.getObservationSize(),obsLayout:n.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(e){console.warn(`Failed to load policy config:`,e)}}}buildPolicyControl(e,t,n){let r=t.getPolicyJointNames(),i=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(n,a,o,s,c,l,u,d)=>{let f=o.qposAdr.length,p=o.actionIndices.map(e=>r[e]),m=this.normalizeControlArray(s,f,1,p),h=this.normalizeControlArray(c,f,0,p),g=d?t.getDefaultJointPos():new Float32Array(r.length),_=new Float32Array(f);for(let e=0;e<f;e++)_[e]=g[o.actionIndices[e]];let v=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(r.length),y=new Float32Array(f);for(let e=0;e<f;e++)y[e]=v[o.actionIndices[e]]??0;let b=this.normalizeControlArray(l,f,0,p),x=this.normalizeControlArray(u,f,0,p),S=o.ctrlAdr.map(e=>e<0||!this.mjModel?!1:this.mjModel.actuator_biastype[e]===i),C=S.some(Boolean),w=S.some(e=>!e);return C&&w&&console.warn(`[PolicyRunner] Action term "${n}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${n}" (${a}): ${f} joint(s), mode: ${C?`position (ctrl=target_pos)`:`motor (ctrl=torque, external PD)`}`),{controlType:a,ctrlAdr:o.ctrlAdr,qposAdr:o.qposAdr,qvelAdr:o.qvelAdr,actionIndices:o.actionIndices,actionScale:m,actionOffset:h,defaultJointPos:_,encoderBias:y,positionActuator:S,kp:b,kd:x,muscleNormalize:!1}},o=e.actions;if(!o||Object.keys(o).length===0){let t=e.control_type??`joint_position`;if(t!==`joint_position`&&t!==`torque`)return console.warn(`[PolicyRunner] Unsupported control_type: ${t}`),null;let r=n.getControlMapping();return r?[a(`legacy`,t,{...r,actionIndices:Array.from({length:r.qposAdr.length},(e,t)=>t)},e.action_scale,void 0,e.stiffness,e.damping,!0)]:(console.warn(`[PolicyRunner] Failed to build control mapping.`),null)}let s=[];for(let[e,t]of Object.entries(o)){let i=t.type??`joint_position`;if(i!==`joint_position`&&i!==`torque`&&i!==`muscle_activation`){console.warn(`[PolicyRunner] Action term "${e}": unsupported type "${i}", skipping.`);continue}let o=t.actuator_names??[`.*`];if(i===`muscle_activation`){let r=n.getCtrlMappingByActuatorNames(o);if(!r){console.warn(`[PolicyRunner] Action term "${e}": no actuators matched patterns [${o.join(`, `)}], skipping.`);continue}let a=r.ctrlAdr.length,c=this.normalizeControlArray(t.scale,a,1),l=this.normalizeControlArray(t.offset,a,0),u=t.normalize??!0;console.log(`[PolicyRunner] Action term "${e}" (muscle_activation): ${a} actuator(s), normalize=${u}`),s.push({controlType:i,ctrlAdr:r.ctrlAdr,qposAdr:[],qvelAdr:[],actionIndices:r.actionIndices,actionScale:c,actionOffset:l,defaultJointPos:new Float32Array(a),encoderBias:new Float32Array(a),positionActuator:Array(a).fill(!1),kp:new Float32Array(a),kd:new Float32Array(a),muscleNormalize:u});continue}let c=o.length===1&&o[0]===`.*`,l;if(c){let t=n.getControlMapping();if(!t){console.warn(`[PolicyRunner] Action term "${e}": failed to build control mapping, skipping.`);continue}l={...t,actionIndices:Array.from({length:t.qposAdr.length},(e,t)=>t)}}else if(l=n.getControlMappingFor(o,r),!l){console.warn(`[PolicyRunner] Action term "${e}": no joints matched patterns [${o.join(`, `)}], skipping.`);continue}let u=t.use_default_offset===void 0?i===`joint_position`:t.use_default_offset;s.push(a(e,i,l,t.scale,t.offset,t.stiffness,t.damping,u))}return s.length===0?(console.warn(`[PolicyRunner] No valid action terms found in config.actions.`),null):s}normalizeControlArray(e,t,n,r){let i=new Float32Array(t);if(i.fill(n),typeof e==`number`)return i.fill(e),i;if(Array.isArray(e)){for(let r=0;r<t;r++)i[r]=typeof e[r]==`number`?e[r]:n;return i}if(typeof e==`object`&&e&&r){for(let[n,a]of Object.entries(e)){let e=r.indexOf(n);e>=0&&e<t?i[e]=a:console.warn(`[PolicyRunner] Joint name "${n}" not found in policy_joint_names; skipping.`)}return i}return i}resetSimulationState(){if(!(!this.mjModel||!this.mjData)){if(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.initialQpos){let e=this.mjData.qpos;for(let t=0;t<Math.min(this.initialQpos.length,this.mjModel.nq);t++)e[t]=this.initialQpos[t]}if(this.initialQvel){let e=this.mjData.qvel;for(let t=0;t<Math.min(this.initialQvel.length,this.mjModel.nv);t++)e[t]=this.initialQvel[t]}this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),this.commandManager.resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState()}}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;let e=this.mjData.ctrl;e.fill(0);let t=this.policyRunner?.getLastActions()??new Float32Array;for(let n of this.policyControl){let{controlType:r,ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s,actionScale:c,actionOffset:l,defaultJointPos:u,encoderBias:d,positionActuator:f,kp:p,kd:m,muscleNormalize:h}=n,g=i.length;if(r===`joint_position`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let h=t[s[n]]??0,g=u[n]+l[n]+c[n]*h-d[n];if(f[n])e[r]=g;else{let t=this.mjData.qpos[a[n]],i=this.mjData.qvel[o[n]];e[r]=p[n]*(g-t)+m[n]*(0-i)}}else if(r===`torque`)for(let n=0;n<g;n++){let r=i[n];r>=0&&(e[r]=c[n]*(t[s[n]]??0))}else if(r===`muscle_activation`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let a=(t[s[n]]??0)*c[n]+l[n];h?e[r]=1/(1+Math.exp(-5*(a-.5))):e[r]=a<0?0:a>1?1:a}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||=this.onnxModule.initInput();let t={...this.onnxInputDict};this.onnxModule.inKeys.includes(`time_step`)&&(t.time_step=new SH(`float32`,new Float32Array([this.onnxTimeStep]),[1,1]));for(let[n,r]of Object.entries(e))t[n]=new SH(`float32`,r,[1,r.length]);for(let e of this.onnxModule.inKeys)if(!t[e]){console.warn(`[PolicyRunner] Missing ONNX input:`,{key:e,available:Object.keys(t)});return}let[n,r]=await this.onnxModule.runInference(t);Object.keys(r).length>0&&(this.onnxInputDict={...this.onnxInputDict,...r}),this.onnxModule.inKeys.includes(`time_step`)&&(this.onnxTimeStep+=1);let i=this.onnxModule.outKeys[0],a=n.action??(i?n[i]:null)??n.policy??null;if(!a)return;let o=a.data,s=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&s.length!==c){console.warn(`[PolicyRunner] Action size mismatch:`,{expected:c,got:s.length});return}this.policyRunner.setLastActions(s)}catch(e){console.warn(`[PolicyRunner] ONNX inference failed:`,e)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let e=0;e<this.mjData.xfrc_applied.length;e++)this.mjData.xfrc_applied[e]=0;let e=this.dragStateManager.physicsObject;if(!e||!(`bodyID`in e)||typeof e.bodyID!=`number`||e.bodyID<=0)return;let t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let e=0;e<this.mjModel.nbody;e++)this.bodies[e]&&(aP(this.mjData.xpos,e,this.bodies[e].position),oP(this.mjData.xquat,e,this.bodies[e].quaternion),this.bodies[e].updateWorldMatrix(!0,!1));this.dragStateManager.update();let n=VN(this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale)),r=VN(this.dragStateManager.worldHit.clone()),i=new Y(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),a=new Y(r.x-i.x,r.y-i.y,r.z-i.z),o=new Y(n.x,n.y,n.z),s=new Y().crossVectors(a,o),c=t*6;this.mjData.xfrc_applied[c+0]=n.x,this.mjData.xfrc_applied[c+1]=n.y,this.mjData.xfrc_applied[c+2]=n.z,this.mjData.xfrc_applied[c+3]=s.x,this.mjData.xfrc_applied[c+4]=s.y,this.mjData.xfrc_applied[c+5]=s.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new Y,quaternion:new Zy});let e=this.lastSimState.bodies.get(t);aP(this.mjData.xpos,t,e.position),oP(this.mjData.xquat,t,e.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&ZN(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=kB(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){let t=new Set;for(let n=1;n<e.nbody;n++){let r=n;for(;r>0;){if(e.body_jntnum[r]>0){t.add(n);break}r=e.body_parentid[r]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;let n=this.bodies[t];n&&(aP(this.mjData.xpos,t,n.position),oP(this.mjData.xquat,t,n.quaternion))}}async captureThumbnail(e={}){let{maxDim:t=1280,quality:n=.85}=e,r=this.renderer.domElement;this.renderer.render(this.scene,this.camera);let i=r.width,a=r.height;if(!i||!a)throw Error(`mjswan: canvas has zero size; nothing to capture.`);let o=Math.min(1,t/Math.max(i,a)),s=Math.max(1,Math.round(i*o)),c=Math.max(1,Math.round(a*o)),l=document.createElement(`canvas`);l.width=s,l.height=c;let u=l.getContext(`2d`);if(!u)throw Error(`mjswan: failed to get a 2D context for thumbnail capture.`);return u.drawImage(r,0,0,s,c),await new Promise((e,t)=>{l.toBlob(n=>n?e(n):t(Error(`mjswan: toBlob returned null.`)),`image/jpeg`,n)})}async dispose(){await this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.onnxModule&&=(this.onnxModule.dispose(),null),this.onnxInputDict=null,this.onnxInferencing=!1,this.splatMesh&&=(Cz(this.splatMesh,this.scene),null),this.colliderMesh&&=(TB(this.colliderMesh,this.scene),null),this.dragStateManager&&=(this.dragStateManager.dispose(),null),this.mjData=null,this.mjModel=null,window.removeEventListener(`resize`,this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear(),this.commandManager.dispose()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{`geometry`in e&&e.geometry&&e.geometry.dispose(),`material`in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){let t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){let e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}};function h1(e){let t=e.config,n={id:e.id,group:e.groupName,type:t.type,label:t.label};return t.type===`slider`?{...n,min:t.min,max:t.max,step:t.step,enabledWhen:t.enabled_when}:n}async function g1(e){return{config:e.config,onnx:await UB(e.onnx),motions:(e.motions??[]).map(e=>({name:e.name,data:e.data,default:e.default})),plugins:e.plugins}}async function _1(e){return{data:await UB(e.data),collider:e.collider?await UB(e.collider):null,transform:e.transform}}var v1=class{constructor(e){this.phase=`paused`,this.loading=!1,this.loadingMessage=null,this.error=null,this.listeners=new Set,this.onCommandEvent=()=>this.refresh(),this.runtime=e,this.state=this.buildState(),this.runtime.commands.addEventListener(this.onCommandEvent),this.camera={set:e=>this.runtime.setCameraView(e),get:()=>this.runtime.getCameraView(),frame:()=>this.runtime.frameCamera()},this.commands={set:(e,t)=>this.runtime.commands.setValue(e,t),trigger:e=>this.runtime.commands.triggerButton(e)}}buildState(){let e=this.runtime.commands;return{phase:this.phase,loading:this.loading,loadingMessage:this.loadingMessage,error:this.error,commands:e.getCommands().map(h1),commandValues:e.getValues()}}refresh(){this.state=this.buildState();for(let e of this.listeners)try{e(this.state)}catch(e){console.warn(`[mjswan] subscribe listener error:`,e)}}async loadScene(e){this.loading=!0,this.loadingMessage=`Loading scene…`,this.error=null,this.refresh();try{let t={model:await UB(e.model),policy:e.policy?await g1(e.policy):null,splat:e.splat?await _1(e.splat):null,viewer:e.viewer??null,events:e.events??null,terrainData:e.terrainData??null,plugins:e.plugins};await this.runtime.loadEnvironment(t),this.phase=this.runtime.isRunning?`running`:`paused`}catch(e){throw this.error=e instanceof Error?e:Error(String(e)),e}finally{this.loading=!1,this.loadingMessage=null,this.refresh()}}async setPolicy(e){await this.runtime.loadPolicyConfig(e?await g1(e):null),this.refresh()}async setSplat(e){await this.runtime.setSplat(e?await _1(e):null)}setMotion(e){return this.runtime.setSelectedMotion(e)}setReferenceVisible(e){this.runtime.setReferenceVisible(e)}calibrateSplat(e){this.runtime.calibrateSplat(e)}play(){this.runtime.play(),this.phase=`running`,this.refresh()}pause(){this.runtime.pause(),this.phase=`paused`,this.refresh()}reset(){this.runtime.resetSimulation()}getState(){return this.state}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}captureThumbnail(e){return this.runtime.captureThumbnail(e)}dispose(){this.runtime.commands.removeEventListener(this.onCommandEvent),this.listeners.clear(),this.runtime.dispose()}};async function y1(e,t={}){return new v1(new m1(await(t.multithreaded?await i(()=>import(`./mujoco-Bacjb_-g.js`),__vite__mapDeps([0,1,2])):await i(()=>import(`./mujoco-CKOf6FiF.js`),__vite__mapDeps([3,1,2]))).default(),e))}globalThis.__mjswanThree=lA;function b1(e){return e.toLowerCase().replace(/ /g,`_`).replace(/-/g,`_`)}function x1(e){return e.id?e.id:`main`}function S1(e,t){let n=t.path?t.path:`scene/${b1(t.name)}/scene.mjz`;return`${x1(e)}/assets/${n}`.replace(/\/+/g,`/`)}function C1(e,t){return`${x1(e)}/assets/${t}`.replace(/\/+/g,`/`)}function w1(e,t){let n=e.lastIndexOf(`/`);return`${n>=0?e.slice(0,n+1):``}${t}`.replace(/\/+/g,`/`)}function T1(e){return async()=>{let t=await fetch(e);if(!t.ok)throw Error(`mjswan/manifest: failed to fetch ${e}: ${t.status}`);return t.arrayBuffer()}}async function E1(e){let t=typeof e==`function`?await e():e;return JSON.parse(new TextDecoder().decode(t))}function D1(e){return{scale:e.scale,xOffset:e.xOffset,yOffset:e.yOffset,zOffset:e.zOffset,roll:e.roll,pitch:e.pitch,yaw:e.yaw}}function O1(e,t,n){return{data:t.path?n(C1(e,t.path)):T1(t.url),collider:t.colliderUrl?/^[a-z]+:\/\//i.test(t.colliderUrl)?T1(t.colliderUrl):n(C1(e,t.colliderUrl)):void 0,transform:D1(t)}}async function k1(e,t,n){if(!t.config)throw Error(`mjswan/manifest: policy "${t.name}" has no config path.`);let r=C1(e,t.config),i=await E1(n(r)),a=i.onnx?.path;if(!a)throw Error(`mjswan/manifest: policy "${t.name}" config missing onnx.path.`);return{config:i,onnx:n(w1(r,a)),motions:Array.isArray(i.motions)?i.motions.map(e=>({name:e.name,data:n(w1(r,e.path)),default:e.default})):[]}}function A1(e,t,n){let r=t.policies.map(t=>({name:t.name,default:t.default??!1,motions:(t.motions??[]).map(e=>({name:e.name,default:e.default??!1})),build:()=>k1(e,t,n)})),i=(t.splats??[]).map(t=>({name:t.name,control:t.control??!1,transform:D1(t),build:async()=>O1(e,t,n)}));return{name:t.name,camera:t.camera,splatSection:t.splatSection??!1,policies:r,splats:i,buildScene:async r=>{let i=r?.policy,a=i==null?t.policies.find(e=>e.default)??t.policies[0]:t.policies.find(e=>e.name===i),o=r?.splat,s=o==null?void 0:t.splats?.find(e=>e.name===o);return{model:n(S1(e,t)),policy:a?await k1(e,a,n):null,splat:s?O1(e,s,n):null,viewer:t.camera,events:t.events,terrainData:t.terrainData}}}}function j1(e,t){let n=typeof e==`string`?JSON.parse(e):e;if(!n.projects?.length)throw Error(`mjswan/manifest: config.json has no projects.`);return{projects:[...n.projects.filter(e=>e.id===null),...n.projects.filter(e=>e.id!==null)].map(e=>({name:e.name,id:e.id,scenes:e.scenes.map(n=>A1(e,n,t))})),pluginsPath:n.plugins}}var M1=`panel`,N1=`ref`;function P1(e){return new URLSearchParams(window.location.search).get(e)!==`0`}function F1(e){return t=>async()=>{let n=`${e}${t}`.replace(/([^:])\/{2,}/g,`$1/`),r=await fetch(n);if(!r.ok)throw Error(`Failed to fetch ${n}: ${r.status}`);return r.arrayBuffer()}}async function I1(e){let t=new URLSearchParams(window.location.search).get(`config`),n=t?new URL(t,window.location.href).toString():`${e}assets/config.json`.replace(/([^:])\/{2,}/g,`$1/`),r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`Failed to fetch ${n}: ${r.status}`);return j1(await r.text(),F1(e))}function L1(e,t,n){if(!t)return n;let r=t.trim().toLowerCase();return e.find(e=>e.name.toLowerCase()===r)??e.find(e=>b1(e.name)===r)??n}function R1(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[a,o]=(0,b.useState)(null),[s,c]=(0,b.useState)(null),[l,u]=(0,b.useState)(null),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),[h,g]=(0,b.useState)(()=>P1(N1)),[_,v]=(0,b.useState)(()=>P1(M1)),[y,x]=(0,b.useState)(null),S=(0,b.useRef)(null),C=(0,b.useRef)(null),w=(0,b.useRef)(null),{showLoading:T,hideLoading:E,setLoadingMessage:D}=Zg(),O=(0,b.useCallback)(e=>{let t=w.current;return t?(e.plugins=t,e.policy&&(e.policy.plugins=t),e):e},[]);(0,b.useEffect)(()=>{T(`Loading…`),I1(`/`).then(async e=>{if(e.pluginsPath){let t=`/${e.pluginsPath}`.replace(/([^:])\/{2,}/g,`$1/`);w.current=await i(()=>import(t),[])}let n=new URLSearchParams(window.location.search),r=L1(e.projects,n.get(`project`),e.projects[0]),a=L1(r?.scenes??[],n.get(`scene`),r?.scenes[0]),s=a?L1(a.policies,n.get(`policy`),a.policies.find(e=>e.default)??a.policies[0]):void 0,l=s?.motions.find(e=>e.default)??s?.motions[0];t(e),o(r?.name??null),c(a?.name??null),u(s?.name??null),f(l?.name??null),m(a?.splats[0]?.name??null)}).catch(e=>{r(e instanceof Error?e.message:String(e)),E(),n_()})},[]);let k=(0,b.useMemo)(()=>e?.projects.find(e=>e.name===a)??e?.projects[0]??null,[e,a]),A=(0,b.useMemo)(()=>k?.scenes.find(e=>e.name===s)??null,[k,s]);(0,b.useEffect)(()=>{let t=S.current;if(!e||!A||!t)return;let n=!1;return(async()=>{T(`Loading MuJoCo…`);let e=await y1(t,{multithreaded:!1});if(n){e.dispose();return}C.current=e,e.subscribe(x);try{D(`Loading scene…`);let t=await A.buildScene({policy:l,splat:p});await e.loadScene(O(t)),d&&await e.setMotion(d),e.setReferenceVisible(h),E(),t_()}catch(e){r(e instanceof Error?e.message:String(e)),E(),n_()}})(),()=>{n=!0,C.current?.dispose(),C.current=null}},[e]),(0,b.useEffect)(()=>{y&&(y.loading?T(y.loadingMessage??`Loading…`):y.error||E(),y.error&&(r(y.error.message),E(),n_()))},[y,T,E]);let j=(0,b.useCallback)(t=>{let n=new URLSearchParams(window.location.search),r=(e,t,r)=>t!=null&&r?n.set(e,t):n.delete(e);r(`project`,t.project??a,(e?.projects.length??0)>1),r(`scene`,t.scene??s,!0),r(`policy`,t.policy??l,!0),n.delete(M1),(t.panel??_)||n.set(M1,`0`),n.delete(N1),(t.ref??h)||n.set(N1,`0`);let i=n.toString();window.history.replaceState({},``,`${window.location.pathname}${i?`?${i}`:``}${window.location.hash}`)},[a,s,l,_,h,e]),M=(0,b.useCallback)(async e=>{let t=C.current;if(!t)return;let n=e.policies.find(e=>e.default)??e.policies[0],r=n?.motions.find(e=>e.default)??n?.motions[0],i=e.splats[0]?.name??null;c(e.name),u(n?.name??null),f(r?.name??null),m(i),j({scene:e.name,policy:n?.name??null}),T(`Loading scene "${e.name}"…`);try{await t.loadScene(O(await e.buildScene({policy:n?.name,splat:i}))),r&&await t.setMotion(r.name),t.setReferenceVisible(h)}catch(e){console.error(`Failed to load scene:`,e)}finally{E()}},[h,j,T,E,O]),N=(0,b.useCallback)(async e=>{let t=k?.scenes.find(t=>t.name===e);t&&await M(t)},[k,M]),P=(0,b.useCallback)(async t=>{let n=e?.projects.find(e=>e.name===t);n&&(o(n.name),j({project:n.name}),n.scenes[0]&&await M(n.scenes[0]))},[e,j,M]),F=(0,b.useCallback)(async e=>{let t=C.current,n=A?.policies.find(t=>t.name===e)??null;u(e);let r=n?.motions.find(e=>e.default)??n?.motions[0];if(f(r?.name??null),j({policy:e}),t){T(e?`Loading policy "${e}"…`:`Clearing policy…`);try{let e=n?await n.build():null;e&&w.current&&(e.plugins=w.current),await t.setPolicy(e),r&&await t.setMotion(r.name),t.setReferenceVisible(h)}catch(e){console.error(`Failed to load policy:`,e)}finally{E()}}},[A,h,j,T,E]),I=(0,b.useCallback)(async e=>{let t=C.current,n=d;if(f(e),t){T(e===null?`Clearing motion…`:`Loading motion "${e}"…`);try{!await t.setMotion(e)&&e!==null&&f(n)}catch(e){console.error(`Failed to load motion:`,e)}finally{E()}}},[d,T,E]),L=(0,b.useCallback)(async e=>{let t=C.current,n=e===null?null:A?.splats.find(t=>t.name===e)??null;if(m(e),!(!t||e!==null&&!n)){T(e===null?`Removing splat…`:`Loading splat "${e}"…`);try{await t.setSplat(n?await n.build():null)}catch(e){console.error(`Failed to load splat:`,e)}finally{E()}}},[A,T,E]),R=(0,b.useCallback)(e=>{g(e),C.current?.setReferenceVisible(e),j({ref:e})},[j]),z=(0,b.useCallback)(e=>{v(e),j({panel:e})},[j]),B=(0,b.useCallback)(e=>e.map(e=>({value:e.name,label:e.name})),[]);return n?(0,G.jsx)(fr,{theme:Yg,defaultColorScheme:`auto`,children:(0,G.jsx)(`div`,{className:`app`,children:(0,G.jsxs)(`div`,{className:`hud hud-error`,children:[(0,G.jsx)(`h1`,{className:`hud-title`,children:`mjswan`}),(0,G.jsx)(`p`,{className:`hud-message`,children:n})]})})}):(0,G.jsx)(fr,{theme:Yg,defaultColorScheme:`auto`,children:(0,G.jsxs)(`div`,{className:`app`,children:[(0,G.jsx)($g,{}),e&&A&&(0,G.jsx)(Gg,{visible:_,onVisibleChange:z,projects:B(e.projects),projectValue:k?.name??null,projectLabel:k?.name??``,onProjectChange:P,scenes:B(k?.scenes??[]),sceneValue:s,onSceneChange:N,splats:B(A.splats),splatSection:A.splatSection,splatValue:p,onSplatChange:L,splatConfig:(()=>{let e=A.splats.find(e=>e.name===p);return e?{name:e.name,control:e.control,...e.transform}:null})(),onCalibrateSplat:(e,t,n,r,i,a,o)=>C.current?.calibrateSplat({scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o}),policies:B(A.policies),policyValue:l,onPolicyChange:F,motions:B(A.policies.find(e=>e.name===l)?.motions??[]),motionValue:d,onMotionChange:I,showReferenceMotion:h,onShowReferenceMotionChange:R,commandsEnabled:!!l,commands:y?.commands?[...y.commands]:[],commandValues:y?.commandValues??{},onCommandChange:(e,t)=>C.current?.commands.set(e,t),onReset:()=>C.current?.reset()}),(0,G.jsx)(`div`,{ref:S,className:`viewer`})]})})}function z1(){return(0,G.jsx)(Qg,{children:(0,G.jsx)(R1,{})})}var B1=document.getElementById(`root`);B1&&(0,wg.createRoot)(B1).render((0,G.jsx)(b.StrictMode,{children:(0,G.jsx)(z1,{})}));