(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))s(l);new MutationObserver(l=>{for(const c of l)if(c.type==="childList")for(const f of c.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&s(f)}).observe(document,{childList:!0,subtree:!0});function i(l){const c={};return l.integrity&&(c.integrity=l.integrity),l.referrerPolicy&&(c.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?c.credentials="include":l.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(l){if(l.ep)return;l.ep=!0;const c=i(l);fetch(l.href,c)}})();function vx(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var kd={exports:{}},ol={};var F_;function wM(){if(F_)return ol;F_=1;var a=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function i(s,l,c){var f=null;if(c!==void 0&&(f=""+c),l.key!==void 0&&(f=""+l.key),"key"in l){c={};for(var p in l)p!=="key"&&(c[p]=l[p])}else c=l;return l=c.ref,{$$typeof:a,type:s,key:f,ref:l!==void 0?l:null,props:c}}return ol.Fragment=e,ol.jsx=i,ol.jsxs=i,ol}var z_;function RM(){return z_||(z_=1,kd.exports=wM()),kd.exports}var g=RM(),jd={exports:{}},Tt={};var H_;function DM(){if(H_)return Tt;H_=1;var a=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),f=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),_=Symbol.iterator;function b(F){return F===null||typeof F!="object"?null:(F=_&&F[_]||F["@@iterator"],typeof F=="function"?F:null)}var T={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,v={};function x(F,J,Ce){this.props=F,this.context=J,this.refs=v,this.updater=Ce||T}x.prototype.isReactComponent={},x.prototype.setState=function(F,J){if(typeof F!="object"&&typeof F!="function"&&F!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,F,J,"setState")},x.prototype.forceUpdate=function(F){this.updater.enqueueForceUpdate(this,F,"forceUpdate")};function B(){}B.prototype=x.prototype;function P(F,J,Ce){this.props=F,this.context=J,this.refs=v,this.updater=Ce||T}var D=P.prototype=new B;D.constructor=P,C(D,x.prototype),D.isPureReactComponent=!0;var O=Array.isArray;function U(){}var N={H:null,A:null,T:null,S:null},A=Object.prototype.hasOwnProperty;function L(F,J,Ce){var Ue=Ce.ref;return{$$typeof:a,type:F,key:J,ref:Ue!==void 0?Ue:null,props:Ce}}function j(F,J){return L(F.type,J,F.props)}function V(F){return typeof F=="object"&&F!==null&&F.$$typeof===a}function $(F){var J={"=":"=0",":":"=2"};return"$"+F.replace(/[=:]/g,function(Ce){return J[Ce]})}var pe=/\/+/g;function ge(F,J){return typeof F=="object"&&F!==null&&F.key!=null?$(""+F.key):J.toString(36)}function K(F){switch(F.status){case"fulfilled":return F.value;case"rejected":throw F.reason;default:switch(typeof F.status=="string"?F.then(U,U):(F.status="pending",F.then(function(J){F.status==="pending"&&(F.status="fulfilled",F.value=J)},function(J){F.status==="pending"&&(F.status="rejected",F.reason=J)})),F.status){case"fulfilled":return F.value;case"rejected":throw F.reason}}throw F}function H(F,J,Ce,Ue,Ie){var ae=typeof F;(ae==="undefined"||ae==="boolean")&&(F=null);var Ae=!1;if(F===null)Ae=!0;else switch(ae){case"bigint":case"string":case"number":Ae=!0;break;case"object":switch(F.$$typeof){case a:case e:Ae=!0;break;case y:return Ae=F._init,H(Ae(F._payload),J,Ce,Ue,Ie)}}if(Ae)return Ie=Ie(F),Ae=Ue===""?"."+ge(F,0):Ue,O(Ie)?(Ce="",Ae!=null&&(Ce=Ae.replace(pe,"$&/")+"/"),H(Ie,J,Ce,"",function(nt){return nt})):Ie!=null&&(V(Ie)&&(Ie=j(Ie,Ce+(Ie.key==null||F&&F.key===Ie.key?"":(""+Ie.key).replace(pe,"$&/")+"/")+Ae)),J.push(Ie)),1;Ae=0;var Ee=Ue===""?".":Ue+":";if(O(F))for(var He=0;He>>1,xe=H[ye];if(0>>1;yel(Ce,ne))Uel(Ie,Ce)?(H[ye]=Ie,H[Ue]=ne,ye=Ue):(H[ye]=Ce,H[J]=ne,ye=J);else if(Uel(Ie,ne))H[ye]=Ie,H[Ue]=ne,ye=Ue;else break e}}return G}function l(H,G){var ne=H.sortIndex-G.sortIndex;return ne!==0?ne:H.id-G.id}if(a.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;a.unstable_now=function(){return c.now()}}else{var f=Date,p=f.now();a.unstable_now=function(){return f.now()-p}}var m=[],h=[],y=1,S=null,_=3,b=!1,T=!1,C=!1,v=!1,x=typeof setTimeout=="function"?setTimeout:null,B=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;function D(H){for(var G=i(h);G!==null;){if(G.callback===null)s(h);else if(G.startTime<=H)s(h),G.sortIndex=G.expirationTime,e(m,G);else break;G=i(h)}}function O(H){if(C=!1,D(H),!T)if(i(m)!==null)T=!0,U||(U=!0,$());else{var G=i(h);G!==null&&K(O,G.startTime-H)}}var U=!1,N=-1,A=5,L=-1;function j(){return v?!0:!(a.unstable_now()-LH&&j());){var ye=S.callback;if(typeof ye=="function"){S.callback=null,_=S.priorityLevel;var xe=ye(S.expirationTime<=H);if(H=a.unstable_now(),typeof xe=="function"){S.callback=xe,D(H),G=!0;break t}S===i(m)&&s(m),D(H)}else s(m);S=i(m)}if(S!==null)G=!0;else{var F=i(h);F!==null&&K(O,F.startTime-H),G=!1}}break e}finally{S=null,_=ne,b=!1}G=void 0}}finally{G?$():U=!1}}}var $;if(typeof P=="function")$=function(){P(V)};else if(typeof MessageChannel<"u"){var pe=new MessageChannel,ge=pe.port2;pe.port1.onmessage=V,$=function(){ge.postMessage(null)}}else $=function(){x(V,0)};function K(H,G){N=x(function(){H(a.unstable_now())},G)}a.unstable_IdlePriority=5,a.unstable_ImmediatePriority=1,a.unstable_LowPriority=4,a.unstable_NormalPriority=3,a.unstable_Profiling=null,a.unstable_UserBlockingPriority=2,a.unstable_cancelCallback=function(H){H.callback=null},a.unstable_forceFrameRate=function(H){0>H||125ye?(H.sortIndex=ne,e(h,H),i(m)===null&&H===i(h)&&(C?(B(N),N=-1):C=!0,K(O,ne-ye))):(H.sortIndex=xe,e(m,H),T||b||(T=!0,U||(U=!0,$()))),H},a.unstable_shouldYield=j,a.unstable_wrapCallback=function(H){var G=_;return function(){var ne=_;_=G;try{return H.apply(this,arguments)}finally{_=ne}}}})(qd)),qd}var k_;function LM(){return k_||(k_=1,Wd.exports=UM()),Wd.exports}var Yd={exports:{}},Yn={};var j_;function OM(){if(j_)return Yn;j_=1;var a=Dp();function e(m){var h="https://react.dev/errors/"+m;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(e){console.error(e)}}return a(),Yd.exports=OM(),Yd.exports}var W_;function IM(){if(W_)return ll;W_=1;var a=LM(),e=Dp(),i=PM();function s(t){var n="https://react.dev/errors/"+t;if(1xe||(t.current=ye[xe],ye[xe]=null,xe--)}function Ce(t,n){xe++,ye[xe]=t.current,t.current=n}var Ue=F(null),Ie=F(null),ae=F(null),Ae=F(null);function Ee(t,n){switch(Ce(ae,n),Ce(Ie,t),Ce(Ue,null),n.nodeType){case 9:case 11:t=(t=n.documentElement)&&(t=t.namespaceURI)?o_(t):0;break;default:if(t=n.tagName,n=n.namespaceURI)n=o_(n),t=l_(n,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}J(Ue),Ce(Ue,t)}function He(){J(Ue),J(Ie),J(ae)}function nt(t){t.memoizedState!==null&&Ce(Ae,t);var n=Ue.current,r=l_(n,t.type);n!==r&&(Ce(Ie,t),Ce(Ue,r))}function Ke(t){Ie.current===t&&(J(Ue),J(Ie)),Ae.current===t&&(J(Ae),il._currentValue=ne)}var zt,ht;function Et(t){if(zt===void 0)try{throw Error()}catch(r){var n=r.stack.trim().match(/\n( *(at )?)/);zt=n&&n[1]||"",ht=-1)":-1u||k[o]!==le[u]){var be=` `+k[o].replace(" at new "," at ");return t.displayName&&be.includes("")&&(be=be.replace("",t.displayName)),be}while(1<=o&&0<=u);break}}}finally{yt=!1,Error.prepareStackTrace=r}return(r=t?t.displayName||t.name:"")?Et(r):""}function Mt(t,n){switch(t.tag){case 26:case 27:case 5:return Et(t.type);case 16:return Et("Lazy");case 13:return t.child!==n&&n!==null?Et("Suspense Fallback"):Et("Suspense");case 19:return Et("SuspenseList");case 0:case 15:return St(t.type,!1);case 11:return St(t.type.render,!1);case 1:return St(t.type,!0);case 31:return Et("Activity");default:return""}}function Ht(t){try{var n="",r=null;do n+=Mt(t,r),r=t,t=t.return;while(t);return n}catch(o){return` Error generating stack: `+o.message+` `+o.stack}}var Gt=Object.prototype.hasOwnProperty,st=a.unstable_scheduleCallback,It=a.unstable_cancelCallback,W=a.unstable_shouldYield,z=a.unstable_requestPaint,Ye=a.unstable_now,xt=a.unstable_getCurrentPriorityLevel,I=a.unstable_ImmediatePriority,E=a.unstable_UserBlockingPriority,X=a.unstable_NormalPriority,se=a.unstable_LowPriority,me=a.unstable_IdlePriority,Ne=a.log,Oe=a.unstable_setDisableYieldValue,_e=null,he=null;function Le(t){if(typeof Ne=="function"&&Oe(t),he&&typeof he.setStrictMode=="function")try{he.setStrictMode(_e,t)}catch{}}var je=Math.clz32?Math.clz32:Qe,ze=Math.log,Fe=Math.LN2;function Qe(t){return t>>>=0,t===0?32:31-(ze(t)/Fe|0)|0}var Je=256,pt=262144,Z=4194304;function Pe(t){var n=t&42;if(n!==0)return n;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Se(t,n,r){var o=t.pendingLanes;if(o===0)return 0;var u=0,d=t.suspendedLanes,M=t.pingedLanes;t=t.warmLanes;var R=o&134217727;return R!==0?(o=R&~d,o!==0?u=Pe(o):(M&=R,M!==0?u=Pe(M):r||(r=R&~t,r!==0&&(u=Pe(r))))):(R=o&~d,R!==0?u=Pe(R):M!==0?u=Pe(M):r||(r=o&~t,r!==0&&(u=Pe(r)))),u===0?0:n!==0&&n!==u&&(n&d)===0&&(d=u&-u,r=n&-n,d>=r||d===32&&(r&4194048)!==0)?n:u}function Be(t,n){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&n)===0}function ke(t,n){switch(t){case 1:case 2:case 4:case 8:case 64:return n+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return n+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function q(){var t=Z;return Z<<=1,(Z&62914560)===0&&(Z=4194304),t}function Me(t){for(var n=[],r=0;31>r;r++)n.push(t);return n}function De(t,n){t.pendingLanes|=n,n!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function ft(t,n,r,o,u,d){var M=t.pendingLanes;t.pendingLanes=r,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=r,t.entangledLanes&=r,t.errorRecoveryDisabledLanes&=r,t.shellSuspendCounter=0;var R=t.entanglements,k=t.expirationTimes,le=t.hiddenUpdates;for(r=M&~r;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Qt=/[\n"\\]/g;function Jt(t){return t.replace(Qt,function(n){return"\\"+n.charCodeAt(0).toString(16)+" "})}function qe(t,n,r,o,u,d,M,R){t.name="",M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"?t.type=M:t.removeAttribute("type"),n!=null?M==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+ct(n)):t.value!==""+ct(n)&&(t.value=""+ct(n)):M!=="submit"&&M!=="reset"||t.removeAttribute("value"),n!=null?Ut(t,M,ct(n)):r!=null?Ut(t,M,ct(r)):o!=null&&t.removeAttribute("value"),u==null&&d!=null&&(t.defaultChecked=!!d),u!=null&&(t.checked=u&&typeof u!="function"&&typeof u!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?t.name=""+ct(R):t.removeAttribute("name")}function qn(t,n,r,o,u,d,M,R){if(d!=null&&typeof d!="function"&&typeof d!="symbol"&&typeof d!="boolean"&&(t.type=d),n!=null||r!=null){if(!(d!=="submit"&&d!=="reset"||n!=null)){Xt(t);return}r=r!=null?""+ct(r):"",n=n!=null?""+ct(n):r,R||n===t.value||(t.value=n),t.defaultValue=n}o=o??u,o=typeof o!="function"&&typeof o!="symbol"&&!!o,t.checked=R?t.checked:!!o,t.defaultChecked=!!o,M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"&&(t.name=M),Xt(t)}function Ut(t,n,r){n==="number"&&cn(t.ownerDocument)===t||t.defaultValue===""+r||(t.defaultValue=""+r)}function Dn(t,n,r,o){if(t=t.options,n){n={};for(var u=0;u"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Vu=!1;if(da)try{var So={};Object.defineProperty(So,"passive",{get:function(){Vu=!0}}),window.addEventListener("test",So,So),window.removeEventListener("test",So,So)}catch{Vu=!1}var Wa=null,ku=null,Ll=null;function lm(){if(Ll)return Ll;var t,n=ku,r=n.length,o,u="value"in Wa?Wa.value:Wa.textContent,d=u.length;for(t=0;t=Eo),pm=" ",mm=!1;function gm(t,n){switch(t){case"keyup":return Ky.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function _m(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var ur=!1;function Qy(t,n){switch(t){case"compositionend":return _m(n);case"keypress":return n.which!==32?null:(mm=!0,pm);case"textInput":return t=n.data,t===pm&&mm?null:t;default:return null}}function Jy(t,n){if(ur)return t==="compositionend"||!Yu&&gm(t,n)?(t=lm(),Ll=ku=Wa=null,ur=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:r,offset:n-t};t=o}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Tm(r)}}function Cm(t,n){return t&&n?t===n?!0:t&&t.nodeType===3?!1:n&&n.nodeType===3?Cm(t,n.parentNode):"contains"in t?t.contains(n):t.compareDocumentPosition?!!(t.compareDocumentPosition(n)&16):!1:!1}function wm(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var n=cn(t.document);n instanceof t.HTMLIFrameElement;){try{var r=typeof n.contentWindow.location.href=="string"}catch{r=!1}if(r)t=n.contentWindow;else break;n=cn(t.document)}return n}function $u(t){var n=t&&t.nodeName&&t.nodeName.toLowerCase();return n&&(n==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||n==="textarea"||t.contentEditable==="true")}var oS=da&&"documentMode"in document&&11>=document.documentMode,fr=null,Qu=null,wo=null,Ju=!1;function Rm(t,n,r){var o=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Ju||fr==null||fr!==cn(o)||(o=fr,"selectionStart"in o&&$u(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),wo&&Co(wo,o)||(wo=o,o=Ac(Qu,"onSelect"),0>=M,u-=M,Qi=1<<32-je(n)+u|r<Rt?(Ft=at,at=null):Ft=at.sibling;var qt=de(te,at,oe[Rt],Te);if(qt===null){at===null&&(at=Ft);break}t&&at&&qt.alternate===null&&n(te,at),Y=d(qt,Y,Rt),Wt===null?ut=qt:Wt.sibling=qt,Wt=qt,at=Ft}if(Rt===oe.length)return r(te,at),Vt&&pa(te,Rt),ut;if(at===null){for(;RtRt?(Ft=at,at=null):Ft=at.sibling;var ps=de(te,at,qt.value,Te);if(ps===null){at===null&&(at=Ft);break}t&&at&&ps.alternate===null&&n(te,at),Y=d(ps,Y,Rt),Wt===null?ut=ps:Wt.sibling=ps,Wt=ps,at=Ft}if(qt.done)return r(te,at),Vt&&pa(te,Rt),ut;if(at===null){for(;!qt.done;Rt++,qt=oe.next())qt=Re(te,qt.value,Te),qt!==null&&(Y=d(qt,Y,Rt),Wt===null?ut=qt:Wt.sibling=qt,Wt=qt);return Vt&&pa(te,Rt),ut}for(at=o(at);!qt.done;Rt++,qt=oe.next())qt=ve(at,te,Rt,qt.value,Te),qt!==null&&(t&&qt.alternate!==null&&at.delete(qt.key===null?Rt:qt.key),Y=d(qt,Y,Rt),Wt===null?ut=qt:Wt.sibling=qt,Wt=qt);return t&&at.forEach(function(CM){return n(te,CM)}),Vt&&pa(te,Rt),ut}function on(te,Y,oe,Te){if(typeof oe=="object"&&oe!==null&&oe.type===C&&oe.key===null&&(oe=oe.props.children),typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case b:e:{for(var ut=oe.key;Y!==null;){if(Y.key===ut){if(ut=oe.type,ut===C){if(Y.tag===7){r(te,Y.sibling),Te=u(Y,oe.props.children),Te.return=te,te=Te;break e}}else if(Y.elementType===ut||typeof ut=="object"&&ut!==null&&ut.$$typeof===A&&Hs(ut)===Y.type){r(te,Y.sibling),Te=u(Y,oe.props),Oo(Te,oe),Te.return=te,te=Te;break e}r(te,Y);break}else n(te,Y);Y=Y.sibling}oe.type===C?(Te=Ps(oe.props.children,te.mode,Te,oe.key),Te.return=te,te=Te):(Te=kl(oe.type,oe.key,oe.props,null,te.mode,Te),Oo(Te,oe),Te.return=te,te=Te)}return M(te);case T:e:{for(ut=oe.key;Y!==null;){if(Y.key===ut)if(Y.tag===4&&Y.stateNode.containerInfo===oe.containerInfo&&Y.stateNode.implementation===oe.implementation){r(te,Y.sibling),Te=u(Y,oe.children||[]),Te.return=te,te=Te;break e}else{r(te,Y);break}else n(te,Y);Y=Y.sibling}Te=of(oe,te.mode,Te),Te.return=te,te=Te}return M(te);case A:return oe=Hs(oe),on(te,Y,oe,Te)}if(K(oe))return tt(te,Y,oe,Te);if($(oe)){if(ut=$(oe),typeof ut!="function")throw Error(s(150));return oe=ut.call(oe),mt(te,Y,oe,Te)}if(typeof oe.then=="function")return on(te,Y,Kl(oe),Te);if(oe.$$typeof===P)return on(te,Y,Wl(te,oe),Te);$l(te,oe)}return typeof oe=="string"&&oe!==""||typeof oe=="number"||typeof oe=="bigint"?(oe=""+oe,Y!==null&&Y.tag===6?(r(te,Y.sibling),Te=u(Y,oe),Te.return=te,te=Te):(r(te,Y),Te=rf(oe,te.mode,Te),Te.return=te,te=Te),M(te)):r(te,Y)}return function(te,Y,oe,Te){try{Lo=0;var ut=on(te,Y,oe,Te);return Mr=null,ut}catch(at){if(at===Sr||at===Yl)throw at;var Wt=mi(29,at,null,te.mode);return Wt.lanes=Te,Wt.return=te,Wt}}}var Vs=Qm(!0),Jm=Qm(!1),$a=!1;function xf(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function yf(t,n){t=t.updateQueue,n.updateQueue===t&&(n.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Qa(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Ja(t,n,r){var o=t.updateQueue;if(o===null)return null;if(o=o.shared,(Yt&2)!==0){var u=o.pending;return u===null?n.next=n:(n.next=u.next,u.next=n),o.pending=n,n=Vl(t),Im(t,null,r),n}return Gl(t,o,n,r),Vl(t)}function Po(t,n,r){if(n=n.updateQueue,n!==null&&(n=n.shared,(r&4194048)!==0)){var o=n.lanes;o&=t.pendingLanes,r|=o,n.lanes=r,Nt(t,r)}}function Sf(t,n){var r=t.updateQueue,o=t.alternate;if(o!==null&&(o=o.updateQueue,r===o)){var u=null,d=null;if(r=r.firstBaseUpdate,r!==null){do{var M={lane:r.lane,tag:r.tag,payload:r.payload,callback:null,next:null};d===null?u=d=M:d=d.next=M,r=r.next}while(r!==null);d===null?u=d=n:d=d.next=n}else u=d=n;r={baseState:o.baseState,firstBaseUpdate:u,lastBaseUpdate:d,shared:o.shared,callbacks:o.callbacks},t.updateQueue=r;return}t=r.lastBaseUpdate,t===null?r.firstBaseUpdate=n:t.next=n,r.lastBaseUpdate=n}var Mf=!1;function Io(){if(Mf){var t=yr;if(t!==null)throw t}}function Bo(t,n,r,o){Mf=!1;var u=t.updateQueue;$a=!1;var d=u.firstBaseUpdate,M=u.lastBaseUpdate,R=u.shared.pending;if(R!==null){u.shared.pending=null;var k=R,le=k.next;k.next=null,M===null?d=le:M.next=le,M=k;var be=t.alternate;be!==null&&(be=be.updateQueue,R=be.lastBaseUpdate,R!==M&&(R===null?be.firstBaseUpdate=le:R.next=le,be.lastBaseUpdate=k))}if(d!==null){var Re=u.baseState;M=0,be=le=k=null,R=d;do{var de=R.lane&-536870913,ve=de!==R.lane;if(ve?(Bt&de)===de:(o&de)===de){de!==0&&de===xr&&(Mf=!0),be!==null&&(be=be.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var tt=t,mt=R;de=n;var on=r;switch(mt.tag){case 1:if(tt=mt.payload,typeof tt=="function"){Re=tt.call(on,Re,de);break e}Re=tt;break e;case 3:tt.flags=tt.flags&-65537|128;case 0:if(tt=mt.payload,de=typeof tt=="function"?tt.call(on,Re,de):tt,de==null)break e;Re=S({},Re,de);break e;case 2:$a=!0}}de=R.callback,de!==null&&(t.flags|=64,ve&&(t.flags|=8192),ve=u.callbacks,ve===null?u.callbacks=[de]:ve.push(de))}else ve={lane:de,tag:R.tag,payload:R.payload,callback:R.callback,next:null},be===null?(le=be=ve,k=Re):be=be.next=ve,M|=de;if(R=R.next,R===null){if(R=u.shared.pending,R===null)break;ve=R,R=ve.next,ve.next=null,u.lastBaseUpdate=ve,u.shared.pending=null}}while(!0);be===null&&(k=Re),u.baseState=k,u.firstBaseUpdate=le,u.lastBaseUpdate=be,d===null&&(u.shared.lanes=0),as|=M,t.lanes=M,t.memoizedState=Re}}function eg(t,n){if(typeof t!="function")throw Error(s(191,t));t.call(n)}function tg(t,n){var r=t.callbacks;if(r!==null)for(t.callbacks=null,t=0;td?d:8;var M=H.T,R={};H.T=R,Gf(t,!1,n,r);try{var k=u(),le=H.S;if(le!==null&&le(R,k),k!==null&&typeof k=="object"&&typeof k.then=="function"){var be=gS(k,o);Ho(t,n,be,yi(t))}else Ho(t,n,o,yi(t))}catch(Re){Ho(t,n,{then:function(){},status:"rejected",reason:Re},yi())}finally{G.p=d,M!==null&&R.types!==null&&(M.types=R.types),H.T=M}}function MS(){}function zf(t,n,r,o){if(t.tag!==5)throw Error(s(476));var u=Lg(t).queue;Ug(t,u,n,ne,r===null?MS:function(){return Og(t),r(o)})}function Lg(t){var n=t.memoizedState;if(n!==null)return n;n={memoizedState:ne,baseState:ne,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:va,lastRenderedState:ne},next:null};var r={};return n.next={memoizedState:r,baseState:r,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:va,lastRenderedState:r},next:null},t.memoizedState=n,t=t.alternate,t!==null&&(t.memoizedState=n),n}function Og(t){var n=Lg(t);n.next===null&&(n=t.alternate.memoizedState),Ho(t,n.next.queue,{},yi())}function Hf(){return kn(il)}function Pg(){return En().memoizedState}function Ig(){return En().memoizedState}function bS(t){for(var n=t.return;n!==null;){switch(n.tag){case 24:case 3:var r=yi();t=Qa(r);var o=Ja(n,t,r);o!==null&&(ri(o,n,r),Po(o,n,r)),n={cache:mf()},t.payload=n;return}n=n.return}}function ES(t,n,r){var o=yi();r={lane:o,revertLane:0,gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},oc(t)?Fg(n,r):(r=af(t,n,r,o),r!==null&&(ri(r,t,o),zg(r,n,o)))}function Bg(t,n,r){var o=yi();Ho(t,n,r,o)}function Ho(t,n,r,o){var u={lane:o,revertLane:0,gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null};if(oc(t))Fg(n,u);else{var d=t.alternate;if(t.lanes===0&&(d===null||d.lanes===0)&&(d=n.lastRenderedReducer,d!==null))try{var M=n.lastRenderedState,R=d(M,r);if(u.hasEagerState=!0,u.eagerState=R,pi(R,M))return Gl(t,n,u,0),un===null&&Hl(),!1}catch{}if(r=af(t,n,u,o),r!==null)return ri(r,t,o),zg(r,n,o),!0}return!1}function Gf(t,n,r,o){if(o={lane:2,revertLane:xd(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},oc(t)){if(n)throw Error(s(479))}else n=af(t,r,o,2),n!==null&&ri(n,t,2)}function oc(t){var n=t.alternate;return t===wt||n!==null&&n===wt}function Fg(t,n){Er=ec=!0;var r=t.pending;r===null?n.next=n:(n.next=r.next,r.next=n),t.pending=n}function zg(t,n,r){if((r&4194048)!==0){var o=n.lanes;o&=t.pendingLanes,r|=o,n.lanes=r,Nt(t,r)}}var Go={readContext:kn,use:ic,useCallback:Sn,useContext:Sn,useEffect:Sn,useImperativeHandle:Sn,useLayoutEffect:Sn,useInsertionEffect:Sn,useMemo:Sn,useReducer:Sn,useRef:Sn,useState:Sn,useDebugValue:Sn,useDeferredValue:Sn,useTransition:Sn,useSyncExternalStore:Sn,useId:Sn,useHostTransitionStatus:Sn,useFormState:Sn,useActionState:Sn,useOptimistic:Sn,useMemoCache:Sn,useCacheRefresh:Sn};Go.useEffectEvent=Sn;var Hg={readContext:kn,use:ic,useCallback:function(t,n){return Qn().memoizedState=[t,n===void 0?null:n],t},useContext:kn,useEffect:bg,useImperativeHandle:function(t,n,r){r=r!=null?r.concat([t]):null,sc(4194308,4,Cg.bind(null,n,t),r)},useLayoutEffect:function(t,n){return sc(4194308,4,t,n)},useInsertionEffect:function(t,n){sc(4,2,t,n)},useMemo:function(t,n){var r=Qn();n=n===void 0?null:n;var o=t();if(ks){Le(!0);try{t()}finally{Le(!1)}}return r.memoizedState=[o,n],o},useReducer:function(t,n,r){var o=Qn();if(r!==void 0){var u=r(n);if(ks){Le(!0);try{r(n)}finally{Le(!1)}}}else u=n;return o.memoizedState=o.baseState=u,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:u},o.queue=t,t=t.dispatch=ES.bind(null,wt,t),[o.memoizedState,t]},useRef:function(t){var n=Qn();return t={current:t},n.memoizedState=t},useState:function(t){t=Of(t);var n=t.queue,r=Bg.bind(null,wt,n);return n.dispatch=r,[t.memoizedState,r]},useDebugValue:Bf,useDeferredValue:function(t,n){var r=Qn();return Ff(r,t,n)},useTransition:function(){var t=Of(!1);return t=Ug.bind(null,wt,t.queue,!0,!1),Qn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,n,r){var o=wt,u=Qn();if(Vt){if(r===void 0)throw Error(s(407));r=r()}else{if(r=n(),un===null)throw Error(s(349));(Bt&127)!==0||og(o,n,r)}u.memoizedState=r;var d={value:r,getSnapshot:n};return u.queue=d,bg(cg.bind(null,o,d,t),[t]),o.flags|=2048,Ar(9,{destroy:void 0},lg.bind(null,o,d,r,n),null),r},useId:function(){var t=Qn(),n=un.identifierPrefix;if(Vt){var r=Ji,o=Qi;r=(o&~(1<<32-je(o)-1)).toString(32)+r,n="_"+n+"R_"+r,r=tc++,0<\/script>",d=d.removeChild(d.firstChild);break;case"select":d=typeof o.is=="string"?M.createElement("select",{is:o.is}):M.createElement("select"),o.multiple?d.multiple=!0:o.size&&(d.size=o.size);break;default:d=typeof o.is=="string"?M.createElement(u,{is:o.is}):M.createElement(u)}}d[we]=n,d[Ge]=o;e:for(M=n.child;M!==null;){if(M.tag===5||M.tag===6)d.appendChild(M.stateNode);else if(M.tag!==4&&M.tag!==27&&M.child!==null){M.child.return=M,M=M.child;continue}if(M===n)break e;for(;M.sibling===null;){if(M.return===null||M.return===n)break e;M=M.return}M.sibling.return=M.return,M=M.sibling}n.stateNode=d;e:switch(Xn(d,u,o),u){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&ya(n)}}return mn(n),td(n,n.type,t===null?null:t.memoizedProps,n.pendingProps,r),null;case 6:if(t&&n.stateNode!=null)t.memoizedProps!==o&&ya(n);else{if(typeof o!="string"&&n.stateNode===null)throw Error(s(166));if(t=ae.current,_r(n)){if(t=n.stateNode,r=n.memoizedProps,o=null,u=Vn,u!==null)switch(u.tag){case 27:case 5:o=u.memoizedProps}t[we]=n,t=!!(t.nodeValue===r||o!==null&&o.suppressHydrationWarning===!0||s_(t.nodeValue,r)),t||Za(n,!0)}else t=Cc(t).createTextNode(o),t[we]=n,n.stateNode=t}return mn(n),null;case 31:if(r=n.memoizedState,t===null||t.memoizedState!==null){if(o=_r(n),r!==null){if(t===null){if(!o)throw Error(s(318));if(t=n.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(s(557));t[we]=n}else Is(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;mn(n),t=!1}else r=ff(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=r),t=!0;if(!t)return n.flags&256?(_i(n),n):(_i(n),null);if((n.flags&128)!==0)throw Error(s(558))}return mn(n),null;case 13:if(o=n.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(u=_r(n),o!==null&&o.dehydrated!==null){if(t===null){if(!u)throw Error(s(318));if(u=n.memoizedState,u=u!==null?u.dehydrated:null,!u)throw Error(s(317));u[we]=n}else Is(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;mn(n),u=!1}else u=ff(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=u),u=!0;if(!u)return n.flags&256?(_i(n),n):(_i(n),null)}return _i(n),(n.flags&128)!==0?(n.lanes=r,n):(r=o!==null,t=t!==null&&t.memoizedState!==null,r&&(o=n.child,u=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(u=o.alternate.memoizedState.cachePool.pool),d=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(d=o.memoizedState.cachePool.pool),d!==u&&(o.flags|=2048)),r!==t&&r&&(n.child.flags|=8192),dc(n,n.updateQueue),mn(n),null);case 4:return He(),t===null&&bd(n.stateNode.containerInfo),mn(n),null;case 10:return ga(n.type),mn(n),null;case 19:if(J(bn),o=n.memoizedState,o===null)return mn(n),null;if(u=(n.flags&128)!==0,d=o.rendering,d===null)if(u)ko(o,!1);else{if(Mn!==0||t!==null&&(t.flags&128)!==0)for(t=n.child;t!==null;){if(d=Jl(t),d!==null){for(n.flags|=128,ko(o,!1),t=d.updateQueue,n.updateQueue=t,dc(n,t),n.subtreeFlags=0,t=r,r=n.child;r!==null;)Bm(r,t),r=r.sibling;return Ce(bn,bn.current&1|2),Vt&&pa(n,o.treeForkCount),n.child}t=t.sibling}o.tail!==null&&Ye()>_c&&(n.flags|=128,u=!0,ko(o,!1),n.lanes=4194304)}else{if(!u)if(t=Jl(d),t!==null){if(n.flags|=128,u=!0,t=t.updateQueue,n.updateQueue=t,dc(n,t),ko(o,!0),o.tail===null&&o.tailMode==="hidden"&&!d.alternate&&!Vt)return mn(n),null}else 2*Ye()-o.renderingStartTime>_c&&r!==536870912&&(n.flags|=128,u=!0,ko(o,!1),n.lanes=4194304);o.isBackwards?(d.sibling=n.child,n.child=d):(t=o.last,t!==null?t.sibling=d:n.child=d,o.last=d)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Ye(),t.sibling=null,r=bn.current,Ce(bn,u?r&1|2:r&1),Vt&&pa(n,o.treeForkCount),t):(mn(n),null);case 22:case 23:return _i(n),Ef(),o=n.memoizedState!==null,t!==null?t.memoizedState!==null!==o&&(n.flags|=8192):o&&(n.flags|=8192),o?(r&536870912)!==0&&(n.flags&128)===0&&(mn(n),n.subtreeFlags&6&&(n.flags|=8192)):mn(n),r=n.updateQueue,r!==null&&dc(n,r.retryQueue),r=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),o=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(o=n.memoizedState.cachePool.pool),o!==r&&(n.flags|=2048),t!==null&&J(zs),null;case 24:return r=null,t!==null&&(r=t.memoizedState.cache),n.memoizedState.cache!==r&&(n.flags|=2048),ga(Tn),mn(n),null;case 25:return null;case 30:return null}throw Error(s(156,n.tag))}function RS(t,n){switch(cf(n),n.tag){case 1:return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 3:return ga(Tn),He(),t=n.flags,(t&65536)!==0&&(t&128)===0?(n.flags=t&-65537|128,n):null;case 26:case 27:case 5:return Ke(n),null;case 31:if(n.memoizedState!==null){if(_i(n),n.alternate===null)throw Error(s(340));Is()}return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 13:if(_i(n),t=n.memoizedState,t!==null&&t.dehydrated!==null){if(n.alternate===null)throw Error(s(340));Is()}return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 19:return J(bn),null;case 4:return He(),null;case 10:return ga(n.type),null;case 22:case 23:return _i(n),Ef(),t!==null&&J(zs),t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 24:return ga(Tn),null;case 25:return null;default:return null}}function u0(t,n){switch(cf(n),n.tag){case 3:ga(Tn),He();break;case 26:case 27:case 5:Ke(n);break;case 4:He();break;case 31:n.memoizedState!==null&&_i(n);break;case 13:_i(n);break;case 19:J(bn);break;case 10:ga(n.type);break;case 22:case 23:_i(n),Ef(),t!==null&&J(zs);break;case 24:ga(Tn)}}function jo(t,n){try{var r=n.updateQueue,o=r!==null?r.lastEffect:null;if(o!==null){var u=o.next;r=u;do{if((r.tag&t)===t){o=void 0;var d=r.create,M=r.inst;o=d(),M.destroy=o}r=r.next}while(r!==u)}}catch(R){nn(n,n.return,R)}}function ns(t,n,r){try{var o=n.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var d=u.next;o=d;do{if((o.tag&t)===t){var M=o.inst,R=M.destroy;if(R!==void 0){M.destroy=void 0,u=n;var k=r,le=R;try{le()}catch(be){nn(u,k,be)}}}o=o.next}while(o!==d)}}catch(be){nn(n,n.return,be)}}function f0(t){var n=t.updateQueue;if(n!==null){var r=t.stateNode;try{tg(n,r)}catch(o){nn(t,t.return,o)}}}function d0(t,n,r){r.props=js(t.type,t.memoizedProps),r.state=t.memoizedState;try{r.componentWillUnmount()}catch(o){nn(t,n,o)}}function Xo(t,n){try{var r=t.ref;if(r!==null){switch(t.tag){case 26:case 27:case 5:var o=t.stateNode;break;case 30:o=t.stateNode;break;default:o=t.stateNode}typeof r=="function"?t.refCleanup=r(o):r.current=o}}catch(u){nn(t,n,u)}}function ea(t,n){var r=t.ref,o=t.refCleanup;if(r!==null)if(typeof o=="function")try{o()}catch(u){nn(t,n,u)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof r=="function")try{r(null)}catch(u){nn(t,n,u)}else r.current=null}function h0(t){var n=t.type,r=t.memoizedProps,o=t.stateNode;try{e:switch(n){case"button":case"input":case"select":case"textarea":r.autoFocus&&o.focus();break e;case"img":r.src?o.src=r.src:r.srcSet&&(o.srcset=r.srcSet)}}catch(u){nn(t,t.return,u)}}function nd(t,n,r){try{var o=t.stateNode;$S(o,t.type,r,n),o[Ge]=n}catch(u){nn(t,t.return,u)}}function p0(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&cs(t.type)||t.tag===4}function id(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||p0(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&cs(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function ad(t,n,r){var o=t.tag;if(o===5||o===6)t=t.stateNode,n?(r.nodeType===9?r.body:r.nodeName==="HTML"?r.ownerDocument.body:r).insertBefore(t,n):(n=r.nodeType===9?r.body:r.nodeName==="HTML"?r.ownerDocument.body:r,n.appendChild(t),r=r._reactRootContainer,r!=null||n.onclick!==null||(n.onclick=fa));else if(o!==4&&(o===27&&cs(t.type)&&(r=t.stateNode,n=null),t=t.child,t!==null))for(ad(t,n,r),t=t.sibling;t!==null;)ad(t,n,r),t=t.sibling}function hc(t,n,r){var o=t.tag;if(o===5||o===6)t=t.stateNode,n?r.insertBefore(t,n):r.appendChild(t);else if(o!==4&&(o===27&&cs(t.type)&&(r=t.stateNode),t=t.child,t!==null))for(hc(t,n,r),t=t.sibling;t!==null;)hc(t,n,r),t=t.sibling}function m0(t){var n=t.stateNode,r=t.memoizedProps;try{for(var o=t.type,u=n.attributes;u.length;)n.removeAttributeNode(u[0]);Xn(n,o,r),n[we]=t,n[Ge]=r}catch(d){nn(t,t.return,d)}}var Sa=!1,wn=!1,sd=!1,g0=typeof WeakSet=="function"?WeakSet:Set,Fn=null;function DS(t,n){if(t=t.containerInfo,Ad=Oc,t=wm(t),$u(t)){if("selectionStart"in t)var r={start:t.selectionStart,end:t.selectionEnd};else e:{r=(r=t.ownerDocument)&&r.defaultView||window;var o=r.getSelection&&r.getSelection();if(o&&o.rangeCount!==0){r=o.anchorNode;var u=o.anchorOffset,d=o.focusNode;o=o.focusOffset;try{r.nodeType,d.nodeType}catch{r=null;break e}var M=0,R=-1,k=-1,le=0,be=0,Re=t,de=null;t:for(;;){for(var ve;Re!==r||u!==0&&Re.nodeType!==3||(R=M+u),Re!==d||o!==0&&Re.nodeType!==3||(k=M+o),Re.nodeType===3&&(M+=Re.nodeValue.length),(ve=Re.firstChild)!==null;)de=Re,Re=ve;for(;;){if(Re===t)break t;if(de===r&&++le===u&&(R=M),de===d&&++be===o&&(k=M),(ve=Re.nextSibling)!==null)break;Re=de,de=Re.parentNode}Re=ve}r=R===-1||k===-1?null:{start:R,end:k}}else r=null}r=r||{start:0,end:0}}else r=null;for(Cd={focusedElem:t,selectionRange:r},Oc=!1,Fn=n;Fn!==null;)if(n=Fn,t=n.child,(n.subtreeFlags&1028)!==0&&t!==null)t.return=n,Fn=t;else for(;Fn!==null;){switch(n=Fn,d=n.alternate,t=n.flags,n.tag){case 0:if((t&4)!==0&&(t=n.updateQueue,t=t!==null?t.events:null,t!==null))for(r=0;r title"))),Xn(d,o,r),d[we]=t,Kt(d),o=d;break e;case"link":var M=M_("link","href",u).get(o+(r.href||""));if(M){for(var R=0;Ron&&(M=on,on=mt,mt=M);var te=Am(R,mt),Y=Am(R,on);if(te&&Y&&(ve.rangeCount!==1||ve.anchorNode!==te.node||ve.anchorOffset!==te.offset||ve.focusNode!==Y.node||ve.focusOffset!==Y.offset)){var oe=Re.createRange();oe.setStart(te.node,te.offset),ve.removeAllRanges(),mt>on?(ve.addRange(oe),ve.extend(Y.node,Y.offset)):(oe.setEnd(Y.node,Y.offset),ve.addRange(oe))}}}}for(Re=[],ve=R;ve=ve.parentNode;)ve.nodeType===1&&Re.push({element:ve,left:ve.scrollLeft,top:ve.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;Rr?32:r,H.T=null,r=dd,dd=null;var d=rs,M=Aa;if(Nn=0,Nr=rs=null,Aa=0,(Yt&6)!==0)throw Error(s(331));var R=Yt;if(Yt|=4,C0(d.current),E0(d,d.current,M,r),Yt=R,$o(0,!1),he&&typeof he.onPostCommitFiberRoot=="function")try{he.onPostCommitFiberRoot(_e,d)}catch{}return!0}finally{G.p=u,H.T=o,X0(t,n)}}function q0(t,n,r){n=Ci(r,n),n=Xf(t.stateNode,n,2),t=Ja(t,n,2),t!==null&&(De(t,2),ta(t))}function nn(t,n,r){if(t.tag===3)q0(t,t,r);else for(;n!==null;){if(n.tag===3){q0(n,t,r);break}else if(n.tag===1){var o=n.stateNode;if(typeof n.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(ss===null||!ss.has(o))){t=Ci(r,t),r=Yg(2),o=Ja(n,r,2),o!==null&&(Zg(r,o,n,t),De(o,2),ta(o));break}}n=n.return}}function gd(t,n,r){var o=t.pingCache;if(o===null){o=t.pingCache=new LS;var u=new Set;o.set(n,u)}else u=o.get(n),u===void 0&&(u=new Set,o.set(n,u));u.has(r)||(ld=!0,u.add(r),t=FS.bind(null,t,n,r),n.then(t,t))}function FS(t,n,r){var o=t.pingCache;o!==null&&o.delete(n),t.pingedLanes|=t.suspendedLanes&r,t.warmLanes&=~r,un===t&&(Bt&r)===r&&(Mn===4||Mn===3&&(Bt&62914560)===Bt&&300>Ye()-gc?(Yt&2)===0&&Ur(t,0):cd|=r,Dr===Bt&&(Dr=0)),ta(t)}function Y0(t,n){n===0&&(n=q()),t=Os(t,n),t!==null&&(De(t,n),ta(t))}function zS(t){var n=t.memoizedState,r=0;n!==null&&(r=n.retryLane),Y0(t,r)}function HS(t,n){var r=0;switch(t.tag){case 31:case 13:var o=t.stateNode,u=t.memoizedState;u!==null&&(r=u.retryLane);break;case 19:o=t.stateNode;break;case 22:o=t.stateNode._retryCache;break;default:throw Error(s(314))}o!==null&&o.delete(n),Y0(t,r)}function GS(t,n){return st(t,n)}var bc=null,Or=null,_d=!1,Ec=!1,vd=!1,ls=0;function ta(t){t!==Or&&t.next===null&&(Or===null?bc=Or=t:Or=Or.next=t),Ec=!0,_d||(_d=!0,kS())}function $o(t,n){if(!vd&&Ec){vd=!0;do for(var r=!1,o=bc;o!==null;){if(t!==0){var u=o.pendingLanes;if(u===0)var d=0;else{var M=o.suspendedLanes,R=o.pingedLanes;d=(1<<31-je(42|t)+1)-1,d&=u&~(M&~R),d=d&201326741?d&201326741|1:d?d|2:0}d!==0&&(r=!0,Q0(o,d))}else d=Bt,d=Se(o,o===un?d:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(d&3)===0||Be(o,d)||(r=!0,Q0(o,d));o=o.next}while(r);vd=!1}}function VS(){Z0()}function Z0(){Ec=_d=!1;var t=0;ls!==0&&JS()&&(t=ls);for(var n=Ye(),r=null,o=bc;o!==null;){var u=o.next,d=K0(o,n);d===0?(o.next=null,r===null?bc=u:r.next=u,u===null&&(Or=r)):(r=o,(t!==0||(d&3)!==0)&&(Ec=!0)),o=u}Nn!==0&&Nn!==5||$o(t),ls!==0&&(ls=0)}function K0(t,n){for(var r=t.suspendedLanes,o=t.pingedLanes,u=t.expirationTimes,d=t.pendingLanes&-62914561;0R)break;var be=k.transferSize,Re=k.initiatorType;be&&r_(Re)&&(k=k.responseEnd,M+=be*(k"u"?null:document;function v_(t,n,r){var o=Pr;if(o&&typeof n=="string"&&n){var u=Jt(n);u='link[rel="'+t+'"][href="'+u+'"]',typeof r=="string"&&(u+='[crossorigin="'+r+'"]'),__.has(u)||(__.add(u),t={rel:t,crossOrigin:r,href:n},o.querySelector(u)===null&&(n=o.createElement("link"),Xn(n,"link",t),Kt(n),o.head.appendChild(n)))}}function lM(t){Ca.D(t),v_("dns-prefetch",t,null)}function cM(t,n){Ca.C(t,n),v_("preconnect",t,n)}function uM(t,n,r){Ca.L(t,n,r);var o=Pr;if(o&&t&&n){var u='link[rel="preload"][as="'+Jt(n)+'"]';n==="image"&&r&&r.imageSrcSet?(u+='[imagesrcset="'+Jt(r.imageSrcSet)+'"]',typeof r.imageSizes=="string"&&(u+='[imagesizes="'+Jt(r.imageSizes)+'"]')):u+='[href="'+Jt(t)+'"]';var d=u;switch(n){case"style":d=Ir(t);break;case"script":d=Br(t)}Li.has(d)||(t=S({rel:"preload",href:n==="image"&&r&&r.imageSrcSet?void 0:t,as:n},r),Li.set(d,t),o.querySelector(u)!==null||n==="style"&&o.querySelector(tl(d))||n==="script"&&o.querySelector(nl(d))||(n=o.createElement("link"),Xn(n,"link",t),Kt(n),o.head.appendChild(n)))}}function fM(t,n){Ca.m(t,n);var r=Pr;if(r&&t){var o=n&&typeof n.as=="string"?n.as:"script",u='link[rel="modulepreload"][as="'+Jt(o)+'"][href="'+Jt(t)+'"]',d=u;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":d=Br(t)}if(!Li.has(d)&&(t=S({rel:"modulepreload",href:t},n),Li.set(d,t),r.querySelector(u)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(r.querySelector(nl(d)))return}o=r.createElement("link"),Xn(o,"link",t),Kt(o),r.head.appendChild(o)}}}function dM(t,n,r){Ca.S(t,n,r);var o=Pr;if(o&&t){var u=Ti(o).hoistableStyles,d=Ir(t);n=n||"default";var M=u.get(d);if(!M){var R={loading:0,preload:null};if(M=o.querySelector(tl(d)))R.loading=5;else{t=S({rel:"stylesheet",href:t,"data-precedence":n},r),(r=Li.get(d))&&Od(t,r);var k=M=o.createElement("link");Kt(k),Xn(k,"link",t),k._p=new Promise(function(le,be){k.onload=le,k.onerror=be}),k.addEventListener("load",function(){R.loading|=1}),k.addEventListener("error",function(){R.loading|=2}),R.loading|=4,Rc(M,n,o)}M={type:"stylesheet",instance:M,count:1,state:R},u.set(d,M)}}}function hM(t,n){Ca.X(t,n);var r=Pr;if(r&&t){var o=Ti(r).hoistableScripts,u=Br(t),d=o.get(u);d||(d=r.querySelector(nl(u)),d||(t=S({src:t,async:!0},n),(n=Li.get(u))&&Pd(t,n),d=r.createElement("script"),Kt(d),Xn(d,"link",t),r.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},o.set(u,d))}}function pM(t,n){Ca.M(t,n);var r=Pr;if(r&&t){var o=Ti(r).hoistableScripts,u=Br(t),d=o.get(u);d||(d=r.querySelector(nl(u)),d||(t=S({src:t,async:!0,type:"module"},n),(n=Li.get(u))&&Pd(t,n),d=r.createElement("script"),Kt(d),Xn(d,"link",t),r.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},o.set(u,d))}}function x_(t,n,r,o){var u=(u=ae.current)?wc(u):null;if(!u)throw Error(s(446));switch(t){case"meta":case"title":return null;case"style":return typeof r.precedence=="string"&&typeof r.href=="string"?(n=Ir(r.href),r=Ti(u).hoistableStyles,o=r.get(n),o||(o={type:"style",instance:null,count:0,state:null},r.set(n,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(r.rel==="stylesheet"&&typeof r.href=="string"&&typeof r.precedence=="string"){t=Ir(r.href);var d=Ti(u).hoistableStyles,M=d.get(t);if(M||(u=u.ownerDocument||u,M={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},d.set(t,M),(d=u.querySelector(tl(t)))&&!d._p&&(M.instance=d,M.state.loading=5),Li.has(t)||(r={rel:"preload",as:"style",href:r.href,crossOrigin:r.crossOrigin,integrity:r.integrity,media:r.media,hrefLang:r.hrefLang,referrerPolicy:r.referrerPolicy},Li.set(t,r),d||mM(u,t,r,M.state))),n&&o===null)throw Error(s(528,""));return M}if(n&&o!==null)throw Error(s(529,""));return null;case"script":return n=r.async,r=r.src,typeof r=="string"&&n&&typeof n!="function"&&typeof n!="symbol"?(n=Br(r),r=Ti(u).hoistableScripts,o=r.get(n),o||(o={type:"script",instance:null,count:0,state:null},r.set(n,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,t))}}function Ir(t){return'href="'+Jt(t)+'"'}function tl(t){return'link[rel="stylesheet"]['+t+"]"}function y_(t){return S({},t,{"data-precedence":t.precedence,precedence:null})}function mM(t,n,r,o){t.querySelector('link[rel="preload"][as="style"]['+n+"]")?o.loading=1:(n=t.createElement("link"),o.preload=n,n.addEventListener("load",function(){return o.loading|=1}),n.addEventListener("error",function(){return o.loading|=2}),Xn(n,"link",r),Kt(n),t.head.appendChild(n))}function Br(t){return'[src="'+Jt(t)+'"]'}function nl(t){return"script[async]"+t}function S_(t,n,r){if(n.count++,n.instance===null)switch(n.type){case"style":var o=t.querySelector('style[data-href~="'+Jt(r.href)+'"]');if(o)return n.instance=o,Kt(o),o;var u=S({},r,{"data-href":r.href,"data-precedence":r.precedence,href:null,precedence:null});return o=(t.ownerDocument||t).createElement("style"),Kt(o),Xn(o,"style",u),Rc(o,r.precedence,t),n.instance=o;case"stylesheet":u=Ir(r.href);var d=t.querySelector(tl(u));if(d)return n.state.loading|=4,n.instance=d,Kt(d),d;o=y_(r),(u=Li.get(u))&&Od(o,u),d=(t.ownerDocument||t).createElement("link"),Kt(d);var M=d;return M._p=new Promise(function(R,k){M.onload=R,M.onerror=k}),Xn(d,"link",o),n.state.loading|=4,Rc(d,r.precedence,t),n.instance=d;case"script":return d=Br(r.src),(u=t.querySelector(nl(d)))?(n.instance=u,Kt(u),u):(o=r,(u=Li.get(d))&&(o=S({},r),Pd(o,u)),t=t.ownerDocument||t,u=t.createElement("script"),Kt(u),Xn(u,"link",o),t.head.appendChild(u),n.instance=u);case"void":return null;default:throw Error(s(443,n.type))}else n.type==="stylesheet"&&(n.state.loading&4)===0&&(o=n.instance,n.state.loading|=4,Rc(o,r.precedence,t));return n.instance}function Rc(t,n,r){for(var o=r.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),u=o.length?o[o.length-1]:null,d=u,M=0;M title"):null)}function gM(t,n,r){if(r===1||n.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof n.precedence!="string"||typeof n.href!="string"||n.href==="")break;return!0;case"link":if(typeof n.rel!="string"||typeof n.href!="string"||n.href===""||n.onLoad||n.onError)break;return n.rel==="stylesheet"?(t=n.disabled,typeof n.precedence=="string"&&t==null):!0;case"script":if(n.async&&typeof n.async!="function"&&typeof n.async!="symbol"&&!n.onLoad&&!n.onError&&n.src&&typeof n.src=="string")return!0}return!1}function E_(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function _M(t,n,r,o){if(r.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(r.state.loading&4)===0){if(r.instance===null){var u=Ir(o.href),d=n.querySelector(tl(u));if(d){n=d._p,n!==null&&typeof n=="object"&&typeof n.then=="function"&&(t.count++,t=Nc.bind(t),n.then(t,t)),r.state.loading|=4,r.instance=d,Kt(d);return}d=n.ownerDocument||n,o=y_(o),(u=Li.get(u))&&Od(o,u),d=d.createElement("link"),Kt(d);var M=d;M._p=new Promise(function(R,k){M.onload=R,M.onerror=k}),Xn(d,"link",o),r.instance=d}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(r,n),(n=r.state.preload)&&(r.state.loading&3)===0&&(t.count++,r=Nc.bind(t),n.addEventListener("load",r),n.addEventListener("error",r))}}var Id=0;function vM(t,n){return t.stylesheets&&t.count===0&&Lc(t,t.stylesheets),0Id?50:800)+n);return t.unsuspend=r,function(){t.unsuspend=null,clearTimeout(o),clearTimeout(u)}}:null}function Nc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Lc(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Uc=null;function Lc(t,n){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Uc=new Map,n.forEach(xM,t),Uc=null,Nc.call(t))}function xM(t,n){if(!(n.state.loading&4)){var r=Uc.get(t);if(r)var o=r.get(null);else{r=new Map,Uc.set(t,r);for(var u=t.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;d"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(e){console.error(e)}}return a(),Xd.exports=IM(),Xd.exports}var FM=BM();const zM=vx(FM),HM="wrap",GM=24;function xx(a){return!!a&&typeof a=="object"&&!Array.isArray(a)}function VM(a,e){return a===void 0||e===void 0?!1:Array.isArray(a)||Array.isArray(e)?!Array.isArray(a)||!Array.isArray(e)?!1:JSON.stringify([...a].sort())===JSON.stringify([...e].sort()):a===e}function Oa(a,e){return e?(a.supported_classes??a.supportedClasses??[]).some(s=>s.dimensions===e.dimensions&&VM(s.states,e.states)&&kM(s,e)):!1}function kM(a,e){return!a.neighborhoodId||!e.neighborhoodId?!0:a.neighborhoodId===e.neighborhoodId}function Ml(a){const e=a?.caClass;if(!xx(e))return;const i=typeof e.dimensions=="number"?e.dimensions:void 0,s=e.states;if(!(!i||typeof s!="number"&&!Array.isArray(s)))return{neighborhoodId:typeof e.neighborhoodId=="string"?e.neighborhoodId:void 0,dimensions:i,states:s}}function jM(a,e,i=GM){const s=xx(a)?a:{},l=Array.isArray(s.size)?s.size:[],c=typeof l[0]=="number"?l[0]:i,f=e>=2&&typeof l[1]=="number"?l[1]:1,p=e>=3&&typeof l[2]=="number"?l[2]:1;return[c,f,p]}function yx(a){let e=2166136261;for(let i=0;i{e+=1831565813;let i=e;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}function XM(a){return a==="wrap"||a==="mirror"||a==="fixed"}function Sx(a){return Uu(a?.simulation?.grid)}function Uu(a){return XM(a?.boundary)?a.boundary:a?.wrap===!1?"fixed":HM}function Mx(a,e){return(a%e+e)%e}function WM(a,e){if(e<=1)return 0;const i=(e-1)*2,s=Mx(a,i);return s<=e-1?s:i-s}function co(a,e,i){return e<=0?null:i==="wrap"?Mx(a,e):i==="mirror"?WM(a,e):a>=0&&a[...e])}function Y_(a,e="cells"){const i=a[0]?.length??0;for(const s of a){if(s.length!==i)throw new Error(`${e} must be rectangular`);for(const l of s)if(typeof l!="boolean")throw new Error(`${e} must contain boolean cell states`)}}function qM(a,e,i="engine output"){if(Y_(a,"input cells"),Y_(e,i),e.length!==a.length||(e[0]?.length??0)!==(a[0]?.length??0))throw new Error(`${i} must preserve the input grid dimensions`)}const bl=new Map;function Ex(a){return a.map(e=>e.map(()=>!1))}function YM(a){const e=/^B([0-8]*)\/S([0-8]*)$/i.exec(a);return e?{birth:new Set(e[1].split("").map(Number)),survival:new Set(e[2].split("").map(Number))}:{birth:new Set([3]),survival:new Set([2,3])}}function ZM(a){const e=/(?:rule[-_\s]*)?(\d{1,3})/i.exec(a??"");return e?Math.max(0,Math.min(255,Number(e[1]))):110}function KM(a,e){return typeof a=="number"&&Number.isFinite(a)?Math.max(0,Math.min(1,a)):e}function Tx(a,e){const i=YM(e.simulation?.ruleId??"B3/S23"),s=Ex(a),l=a.length,c=a[0]?.length??0,f=Uu(e.simulation?.grid);for(let p=0;pm.some(Boolean))),p=a[f]??[];for(let m=0;m>T&1)===1}return s}function QM(a,e,i){return yx(`${a}:${e}:${i}`)()}function JM(a,e){const i=Ex(a),s=a.length,l=a[0]?.length??0,c=Uu(e.simulation?.grid),f=KM(e.simulation?.spreadProbability,1),p=typeof e.simulation?.seed=="string"?e.simulation.seed:"wildfire";for(let m=0;m0&&QM(p,h,m)=0;--e)if(a[e]>=65535)return!0;return!1}function wu(a){return document.createElementNS("http://www.w3.org/1999/xhtml",a)}function Fb(){const a=wu("canvas");return a.style.display="block",a}const nv={};function iv(...a){const e="THREE."+a.shift();console.log(e,...a)}function Gx(a){const e=a[0];if(typeof e=="string"&&e.startsWith("TSL:")){const i=a[1];i&&i.isStackTrace?a[0]+=" "+i.getLocation():a[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return a}function _t(...a){a=Gx(a);const e="THREE."+a.shift();{const i=a[0];i&&i.isStackTrace?console.warn(i.getError(e)):console.warn(e,...a)}}function jt(...a){a=Gx(a);const e="THREE."+a.shift();{const i=a[0];i&&i.isStackTrace?console.error(i.getError(e)):console.error(e,...a)}}function so(...a){const e=a.join(" ");e in nv||(nv[e]=!0,_t(...a))}function zb(a,e,i){return new Promise(function(s,l){function c(){switch(a.clientWaitSync(e,a.SYNC_FLUSH_COMMANDS_BIT,0)){case a.WAIT_FAILED:l();break;case a.TIMEOUT_EXPIRED:setTimeout(c,i);break;default:s()}}setTimeout(c,i)})}const Hb={[Ih]:Bh,[Fh]:Gh,[zh]:Vh,[uo]:Hh,[Bh]:Ih,[Gh]:Fh,[Vh]:zh,[Hh]:uo};class Rs{addEventListener(e,i){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(i)===-1&&s[e].push(i)}hasEventListener(e,i){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(i)!==-1}removeEventListener(e,i){const s=this._listeners;if(s===void 0)return;const l=s[e];if(l!==void 0){const c=l.indexOf(i);c!==-1&&l.splice(c,1)}}dispatchEvent(e){const i=this._listeners;if(i===void 0)return;const s=i[e.type];if(s!==void 0){e.target=this;const l=s.slice(0);for(let c=0,f=l.length;c>8&255]+Zn[a>>16&255]+Zn[a>>24&255]+"-"+Zn[e&255]+Zn[e>>8&255]+"-"+Zn[e>>16&15|64]+Zn[e>>24&255]+"-"+Zn[i&63|128]+Zn[i>>8&255]+"-"+Zn[i>>16&255]+Zn[i>>24&255]+Zn[s&255]+Zn[s>>8&255]+Zn[s>>16&255]+Zn[s>>24&255]).toLowerCase()}function Pt(a,e,i){return Math.max(e,Math.min(i,a))}function Gb(a,e){return(a%e+e)%e}function Qd(a,e,i){return(1-i)*a+i*e}function cl(a,e){switch(e.constructor){case Float32Array:return a;case Uint32Array:return a/4294967295;case Uint16Array:return a/65535;case Uint8Array:return a/255;case Int32Array:return Math.max(a/2147483647,-1);case Int16Array:return Math.max(a/32767,-1);case Int8Array:return Math.max(a/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function oi(a,e){switch(e.constructor){case Float32Array:return a;case Uint32Array:return Math.round(a*4294967295);case Uint16Array:return Math.round(a*65535);case Uint8Array:return Math.round(a*255);case Int32Array:return Math.round(a*2147483647);case Int16Array:return Math.round(a*32767);case Int8Array:return Math.round(a*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const Vb={DEG2RAD:El},tm=class tm{constructor(e=0,i=0){this.x=e,this.y=i}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,i){return this.x=e,this.y=i,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,i){switch(e){case 0:this.x=i;break;case 1:this.y=i;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: 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,i){return this.x=e.x+i.x,this.y=e.y+i.y,this}addScaledVector(e,i){return this.x+=e.x*i,this.y+=e.y*i,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,i){return this.x=e.x-i.x,this.y=e.y-i.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const i=this.x,s=this.y,l=e.elements;return this.x=l[0]*i+l[3]*s+l[6],this.y=l[1]*i+l[4]*s+l[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,i){return this.x=Pt(this.x,e.x,i.x),this.y=Pt(this.y,e.y,i.y),this}clampScalar(e,i){return this.x=Pt(this.x,e,i),this.y=Pt(this.y,e,i),this}clampLength(e,i){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Pt(s,e,i))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const i=Math.sqrt(this.lengthSq()*e.lengthSq());if(i===0)return Math.PI/2;const s=this.dot(e)/i;return Math.acos(Pt(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const i=this.x-e.x,s=this.y-e.y;return i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,i){return this.x+=(e.x-this.x)*i,this.y+=(e.y-this.y)*i,this}lerpVectors(e,i,s){return this.x=e.x+(i.x-e.x)*s,this.y=e.y+(i.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,i=0){return this.x=e[i],this.y=e[i+1],this}toArray(e=[],i=0){return e[i]=this.x,e[i+1]=this.y,e}fromBufferAttribute(e,i){return this.x=e.getX(i),this.y=e.getY(i),this}rotateAround(e,i){const s=Math.cos(i),l=Math.sin(i),c=this.x-e.x,f=this.y-e.y;return this.x=c*s-f*l+e.x,this.y=c*l+f*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};tm.prototype.isVector2=!0;let bt=tm;class As{constructor(e=0,i=0,s=0,l=1){this.isQuaternion=!0,this._x=e,this._y=i,this._z=s,this._w=l}static slerpFlat(e,i,s,l,c,f,p){let m=s[l+0],h=s[l+1],y=s[l+2],S=s[l+3],_=c[f+0],b=c[f+1],T=c[f+2],C=c[f+3];if(S!==C||m!==_||h!==b||y!==T){let v=m*_+h*b+y*T+S*C;v<0&&(_=-_,b=-b,T=-T,C=-C,v=-v);let x=1-p;if(v<.9995){const B=Math.acos(v),P=Math.sin(B);x=Math.sin(x*B)/P,p=Math.sin(p*B)/P,m=m*x+_*p,h=h*x+b*p,y=y*x+T*p,S=S*x+C*p}else{m=m*x+_*p,h=h*x+b*p,y=y*x+T*p,S=S*x+C*p;const B=1/Math.sqrt(m*m+h*h+y*y+S*S);m*=B,h*=B,y*=B,S*=B}}e[i]=m,e[i+1]=h,e[i+2]=y,e[i+3]=S}static multiplyQuaternionsFlat(e,i,s,l,c,f){const p=s[l],m=s[l+1],h=s[l+2],y=s[l+3],S=c[f],_=c[f+1],b=c[f+2],T=c[f+3];return e[i]=p*T+y*S+m*b-h*_,e[i+1]=m*T+y*_+h*S-p*b,e[i+2]=h*T+y*b+p*_-m*S,e[i+3]=y*T-p*S-m*_-h*b,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,i,s,l){return this._x=e,this._y=i,this._z=s,this._w=l,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,i=!0){const s=e._x,l=e._y,c=e._z,f=e._order,p=Math.cos,m=Math.sin,h=p(s/2),y=p(l/2),S=p(c/2),_=m(s/2),b=m(l/2),T=m(c/2);switch(f){case"XYZ":this._x=_*y*S+h*b*T,this._y=h*b*S-_*y*T,this._z=h*y*T+_*b*S,this._w=h*y*S-_*b*T;break;case"YXZ":this._x=_*y*S+h*b*T,this._y=h*b*S-_*y*T,this._z=h*y*T-_*b*S,this._w=h*y*S+_*b*T;break;case"ZXY":this._x=_*y*S-h*b*T,this._y=h*b*S+_*y*T,this._z=h*y*T+_*b*S,this._w=h*y*S-_*b*T;break;case"ZYX":this._x=_*y*S-h*b*T,this._y=h*b*S+_*y*T,this._z=h*y*T-_*b*S,this._w=h*y*S+_*b*T;break;case"YZX":this._x=_*y*S+h*b*T,this._y=h*b*S+_*y*T,this._z=h*y*T-_*b*S,this._w=h*y*S-_*b*T;break;case"XZY":this._x=_*y*S-h*b*T,this._y=h*b*S-_*y*T,this._z=h*y*T+_*b*S,this._w=h*y*S+_*b*T;break;default:_t("Quaternion: .setFromEuler() encountered an unknown order: "+f)}return i===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,i){const s=i/2,l=Math.sin(s);return this._x=e.x*l,this._y=e.y*l,this._z=e.z*l,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const i=e.elements,s=i[0],l=i[4],c=i[8],f=i[1],p=i[5],m=i[9],h=i[2],y=i[6],S=i[10],_=s+p+S;if(_>0){const b=.5/Math.sqrt(_+1);this._w=.25/b,this._x=(y-m)*b,this._y=(c-h)*b,this._z=(f-l)*b}else if(s>p&&s>S){const b=2*Math.sqrt(1+s-p-S);this._w=(y-m)/b,this._x=.25*b,this._y=(l+f)/b,this._z=(c+h)/b}else if(p>S){const b=2*Math.sqrt(1+p-s-S);this._w=(c-h)/b,this._x=(l+f)/b,this._y=.25*b,this._z=(m+y)/b}else{const b=2*Math.sqrt(1+S-s-p);this._w=(f-l)/b,this._x=(c+h)/b,this._y=(m+y)/b,this._z=.25*b}return this._onChangeCallback(),this}setFromUnitVectors(e,i){let s=e.dot(i)+1;return s<1e-8?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*i.z-e.z*i.y,this._y=e.z*i.x-e.x*i.z,this._z=e.x*i.y-e.y*i.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Pt(this.dot(e),-1,1)))}rotateTowards(e,i){const s=this.angleTo(e);if(s===0)return this;const l=Math.min(1,i/s);return this.slerp(e,l),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,i){const s=e._x,l=e._y,c=e._z,f=e._w,p=i._x,m=i._y,h=i._z,y=i._w;return this._x=s*y+f*p+l*h-c*m,this._y=l*y+f*m+c*p-s*h,this._z=c*y+f*h+s*m-l*p,this._w=f*y-s*p-l*m-c*h,this._onChangeCallback(),this}slerp(e,i){let s=e._x,l=e._y,c=e._z,f=e._w,p=this.dot(e);p<0&&(s=-s,l=-l,c=-c,f=-f,p=-p);let m=1-i;if(p<.9995){const h=Math.acos(p),y=Math.sin(h);m=Math.sin(m*h)/y,i=Math.sin(i*h)/y,this._x=this._x*m+s*i,this._y=this._y*m+l*i,this._z=this._z*m+c*i,this._w=this._w*m+f*i,this._onChangeCallback()}else this._x=this._x*m+s*i,this._y=this._y*m+l*i,this._z=this._z*m+c*i,this._w=this._w*m+f*i,this.normalize();return this}slerpQuaternions(e,i,s){return this.copy(e).slerp(i,s)}random(){const e=2*Math.PI*Math.random(),i=2*Math.PI*Math.random(),s=Math.random(),l=Math.sqrt(1-s),c=Math.sqrt(s);return this.set(l*Math.sin(e),l*Math.cos(e),c*Math.sin(i),c*Math.cos(i))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,i=0){return this._x=e[i],this._y=e[i+1],this._z=e[i+2],this._w=e[i+3],this._onChangeCallback(),this}toArray(e=[],i=0){return e[i]=this._x,e[i+1]=this._y,e[i+2]=this._z,e[i+3]=this._w,e}fromBufferAttribute(e,i){return this._x=e.getX(i),this._y=e.getY(i),this._z=e.getZ(i),this._w=e.getW(i),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}}const nm=class nm{constructor(e=0,i=0,s=0){this.x=e,this.y=i,this.z=s}set(e,i,s){return s===void 0&&(s=this.z),this.x=e,this.y=i,this.z=s,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,i){switch(e){case 0:this.x=i;break;case 1:this.y=i;break;case 2:this.z=i;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: 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,i){return this.x=e.x+i.x,this.y=e.y+i.y,this.z=e.z+i.z,this}addScaledVector(e,i){return this.x+=e.x*i,this.y+=e.y*i,this.z+=e.z*i,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,i){return this.x=e.x-i.x,this.y=e.y-i.y,this.z=e.z-i.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,i){return this.x=e.x*i.x,this.y=e.y*i.y,this.z=e.z*i.z,this}applyEuler(e){return this.applyQuaternion(av.setFromEuler(e))}applyAxisAngle(e,i){return this.applyQuaternion(av.setFromAxisAngle(e,i))}applyMatrix3(e){const i=this.x,s=this.y,l=this.z,c=e.elements;return this.x=c[0]*i+c[3]*s+c[6]*l,this.y=c[1]*i+c[4]*s+c[7]*l,this.z=c[2]*i+c[5]*s+c[8]*l,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const i=this.x,s=this.y,l=this.z,c=e.elements,f=1/(c[3]*i+c[7]*s+c[11]*l+c[15]);return this.x=(c[0]*i+c[4]*s+c[8]*l+c[12])*f,this.y=(c[1]*i+c[5]*s+c[9]*l+c[13])*f,this.z=(c[2]*i+c[6]*s+c[10]*l+c[14])*f,this}applyQuaternion(e){const i=this.x,s=this.y,l=this.z,c=e.x,f=e.y,p=e.z,m=e.w,h=2*(f*l-p*s),y=2*(p*i-c*l),S=2*(c*s-f*i);return this.x=i+m*h+f*S-p*y,this.y=s+m*y+p*h-c*S,this.z=l+m*S+c*y-f*h,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const i=this.x,s=this.y,l=this.z,c=e.elements;return this.x=c[0]*i+c[4]*s+c[8]*l,this.y=c[1]*i+c[5]*s+c[9]*l,this.z=c[2]*i+c[6]*s+c[10]*l,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,i){return this.x=Pt(this.x,e.x,i.x),this.y=Pt(this.y,e.y,i.y),this.z=Pt(this.z,e.z,i.z),this}clampScalar(e,i){return this.x=Pt(this.x,e,i),this.y=Pt(this.y,e,i),this.z=Pt(this.z,e,i),this}clampLength(e,i){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Pt(s,e,i))}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,i){return this.x+=(e.x-this.x)*i,this.y+=(e.y-this.y)*i,this.z+=(e.z-this.z)*i,this}lerpVectors(e,i,s){return this.x=e.x+(i.x-e.x)*s,this.y=e.y+(i.y-e.y)*s,this.z=e.z+(i.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,i){const s=e.x,l=e.y,c=e.z,f=i.x,p=i.y,m=i.z;return this.x=l*m-c*p,this.y=c*f-s*m,this.z=s*p-l*f,this}projectOnVector(e){const i=e.lengthSq();if(i===0)return this.set(0,0,0);const s=e.dot(this)/i;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Jd.copy(this).projectOnVector(e),this.sub(Jd)}reflect(e){return this.sub(Jd.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const i=Math.sqrt(this.lengthSq()*e.lengthSq());if(i===0)return Math.PI/2;const s=this.dot(e)/i;return Math.acos(Pt(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const i=this.x-e.x,s=this.y-e.y,l=this.z-e.z;return i*i+s*s+l*l}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,i,s){const l=Math.sin(i)*e;return this.x=l*Math.sin(s),this.y=Math.cos(i)*e,this.z=l*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,i,s){return this.x=e*Math.sin(i),this.y=s,this.z=e*Math.cos(i),this}setFromMatrixPosition(e){const i=e.elements;return this.x=i[12],this.y=i[13],this.z=i[14],this}setFromMatrixScale(e){const i=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),l=this.setFromMatrixColumn(e,2).length();return this.x=i,this.y=s,this.z=l,this}setFromMatrixColumn(e,i){return this.fromArray(e.elements,i*4)}setFromMatrix3Column(e,i){return this.fromArray(e.elements,i*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,i=0){return this.x=e[i],this.y=e[i+1],this.z=e[i+2],this}toArray(e=[],i=0){return e[i]=this.x,e[i+1]=this.y,e[i+2]=this.z,e}fromBufferAttribute(e,i){return this.x=e.getX(i),this.y=e.getY(i),this.z=e.getZ(i),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,i=Math.random()*2-1,s=Math.sqrt(1-i*i);return this.x=s*Math.cos(e),this.y=i,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};nm.prototype.isVector3=!0;let ie=nm;const Jd=new ie,av=new As,im=class im{constructor(e,i,s,l,c,f,p,m,h){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,i,s,l,c,f,p,m,h)}set(e,i,s,l,c,f,p,m,h){const y=this.elements;return y[0]=e,y[1]=l,y[2]=p,y[3]=i,y[4]=c,y[5]=m,y[6]=s,y[7]=f,y[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const i=this.elements,s=e.elements;return i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],i[4]=s[4],i[5]=s[5],i[6]=s[6],i[7]=s[7],i[8]=s[8],this}extractBasis(e,i,s){return e.setFromMatrix3Column(this,0),i.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const i=e.elements;return this.set(i[0],i[4],i[8],i[1],i[5],i[9],i[2],i[6],i[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,i){const s=e.elements,l=i.elements,c=this.elements,f=s[0],p=s[3],m=s[6],h=s[1],y=s[4],S=s[7],_=s[2],b=s[5],T=s[8],C=l[0],v=l[3],x=l[6],B=l[1],P=l[4],D=l[7],O=l[2],U=l[5],N=l[8];return c[0]=f*C+p*B+m*O,c[3]=f*v+p*P+m*U,c[6]=f*x+p*D+m*N,c[1]=h*C+y*B+S*O,c[4]=h*v+y*P+S*U,c[7]=h*x+y*D+S*N,c[2]=_*C+b*B+T*O,c[5]=_*v+b*P+T*U,c[8]=_*x+b*D+T*N,this}multiplyScalar(e){const i=this.elements;return i[0]*=e,i[3]*=e,i[6]*=e,i[1]*=e,i[4]*=e,i[7]*=e,i[2]*=e,i[5]*=e,i[8]*=e,this}determinant(){const e=this.elements,i=e[0],s=e[1],l=e[2],c=e[3],f=e[4],p=e[5],m=e[6],h=e[7],y=e[8];return i*f*y-i*p*h-s*c*y+s*p*m+l*c*h-l*f*m}invert(){const e=this.elements,i=e[0],s=e[1],l=e[2],c=e[3],f=e[4],p=e[5],m=e[6],h=e[7],y=e[8],S=y*f-p*h,_=p*m-y*c,b=h*c-f*m,T=i*S+s*_+l*b;if(T===0)return this.set(0,0,0,0,0,0,0,0,0);const C=1/T;return e[0]=S*C,e[1]=(l*h-y*s)*C,e[2]=(p*s-l*f)*C,e[3]=_*C,e[4]=(y*i-l*m)*C,e[5]=(l*c-p*i)*C,e[6]=b*C,e[7]=(s*m-h*i)*C,e[8]=(f*i-s*c)*C,this}transpose(){let e;const i=this.elements;return e=i[1],i[1]=i[3],i[3]=e,e=i[2],i[2]=i[6],i[6]=e,e=i[5],i[5]=i[7],i[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const i=this.elements;return e[0]=i[0],e[1]=i[3],e[2]=i[6],e[3]=i[1],e[4]=i[4],e[5]=i[7],e[6]=i[2],e[7]=i[5],e[8]=i[8],this}setUvTransform(e,i,s,l,c,f,p){const m=Math.cos(c),h=Math.sin(c);return this.set(s*m,s*h,-s*(m*f+h*p)+f+e,-l*h,l*m,-l*(-h*f+m*p)+p+i,0,0,1),this}scale(e,i){return so("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(eh.makeScale(e,i)),this}rotate(e){return so("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(eh.makeRotation(-e)),this}translate(e,i){return so("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(eh.makeTranslation(e,i)),this}makeTranslation(e,i){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,i,0,0,1),this}makeRotation(e){const i=Math.cos(e),s=Math.sin(e);return this.set(i,-s,0,s,i,0,0,0,1),this}makeScale(e,i){return this.set(e,0,0,0,i,0,0,0,1),this}equals(e){const i=this.elements,s=e.elements;for(let l=0;l<9;l++)if(i[l]!==s[l])return!1;return!0}fromArray(e,i=0){for(let s=0;s<9;s++)this.elements[s]=e[s+i];return this}toArray(e=[],i=0){const s=this.elements;return e[i]=s[0],e[i+1]=s[1],e[i+2]=s[2],e[i+3]=s[3],e[i+4]=s[4],e[i+5]=s[5],e[i+6]=s[6],e[i+7]=s[7],e[i+8]=s[8],e}clone(){return new this.constructor().fromArray(this.elements)}};im.prototype.isMatrix3=!0;let At=im;const eh=new At,sv=new At().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),rv=new At().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function kb(){const a={enabled:!0,workingColorSpace:Au,spaces:{},convert:function(l,c,f){return this.enabled===!1||c===f||!c||!f||(this.spaces[c].transfer===an&&(l.r=Fa(l.r),l.g=Fa(l.g),l.b=Fa(l.b)),this.spaces[c].primaries!==this.spaces[f].primaries&&(l.applyMatrix3(this.spaces[c].toXYZ),l.applyMatrix3(this.spaces[f].fromXYZ)),this.spaces[f].transfer===an&&(l.r=ro(l.r),l.g=ro(l.g),l.b=ro(l.b))),l},workingToColorSpace:function(l,c){return this.convert(l,this.workingColorSpace,c)},colorSpaceToWorking:function(l,c){return this.convert(l,c,this.workingColorSpace)},getPrimaries:function(l){return this.spaces[l].primaries},getTransfer:function(l){return l===Ms?Cu:this.spaces[l].transfer},getToneMappingMode:function(l){return this.spaces[l].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(l,c=this.workingColorSpace){return l.fromArray(this.spaces[c].luminanceCoefficients)},define:function(l){Object.assign(this.spaces,l)},_getMatrix:function(l,c,f){return l.copy(this.spaces[c].toXYZ).multiply(this.spaces[f].fromXYZ)},_getDrawingBufferColorSpace:function(l){return this.spaces[l].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(l=this.workingColorSpace){return this.spaces[l].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(l,c){return so("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),a.workingToColorSpace(l,c)},toWorkingColorSpace:function(l,c){return so("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),a.colorSpaceToWorking(l,c)}},e=[.64,.33,.3,.6,.15,.06],i=[.2126,.7152,.0722],s=[.3127,.329];return a.define({[Au]:{primaries:e,whitePoint:s,transfer:Cu,toXYZ:sv,fromXYZ:rv,luminanceCoefficients:i,workingColorSpaceConfig:{unpackColorSpace:bi},outputColorSpaceConfig:{drawingBufferColorSpace:bi}},[bi]:{primaries:e,whitePoint:s,transfer:an,toXYZ:sv,fromXYZ:rv,luminanceCoefficients:i,outputColorSpaceConfig:{drawingBufferColorSpace:bi}}}),a}const kt=kb();function Fa(a){return a<.04045?a*.0773993808:Math.pow(a*.9478672986+.0521327014,2.4)}function ro(a){return a<.0031308?a*12.92:1.055*Math.pow(a,.41666)-.055}let Hr;class jb{static getDataURL(e,i="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{Hr===void 0&&(Hr=wu("canvas")),Hr.width=e.width,Hr.height=e.height;const l=Hr.getContext("2d");e instanceof ImageData?l.putImageData(e,0,0):l.drawImage(e,0,0,e.width,e.height),s=Hr}return s.toDataURL(i)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const i=wu("canvas");i.width=e.width,i.height=e.height;const s=i.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const l=s.getImageData(0,0,e.width,e.height),c=l.data;for(let f=0;f1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(nh).x}get height(){return this.source.getSize(nh).y}get depth(){return this.source.getSize(nh).z}get image(){return this.source.data}set image(e){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,i){this.updateRanges.push({start:e,count:i})}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.normalized=e.normalized,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(const i in e){const s=e[i];if(s===void 0){_t(`Texture.setValues(): parameter '${i}' has value of undefined.`);continue}const l=this[i];if(l===void 0){_t(`Texture.setValues(): property '${i}' does not exist.`);continue}l&&s&&l.isVector2&&s.isVector2||l&&s&&l.isVector3&&s.isVector3||l&&s&&l.isMatrix3&&s.isMatrix3?l.copy(s):this[i]=s}}toJSON(e){const i=e===void 0||typeof e=="string";if(!i&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const s={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,normalized:this.normalized,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&&(s.userData=this.userData),i||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Ox)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case kh:e.x=e.x-Math.floor(e.x);break;case Ia:e.x=e.x<0?0:1;break;case jh:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case kh:e.y=e.y-Math.floor(e.y);break;case Ia:e.y=e.y<0?0:1;break;case jh:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}ei.DEFAULT_IMAGE=null;ei.DEFAULT_MAPPING=Ox;ei.DEFAULT_ANISOTROPY=1;const am=class am{constructor(e=0,i=0,s=0,l=1){this.x=e,this.y=i,this.z=s,this.w=l}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,i,s,l){return this.x=e,this.y=i,this.z=s,this.w=l,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,i){switch(e){case 0:this.x=i;break;case 1:this.y=i;break;case 2:this.z=i;break;case 3:this.w=i;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,i){return this.x=e.x+i.x,this.y=e.y+i.y,this.z=e.z+i.z,this.w=e.w+i.w,this}addScaledVector(e,i){return this.x+=e.x*i,this.y+=e.y*i,this.z+=e.z*i,this.w+=e.w*i,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,i){return this.x=e.x-i.x,this.y=e.y-i.y,this.z=e.z-i.z,this.w=e.w-i.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const i=this.x,s=this.y,l=this.z,c=this.w,f=e.elements;return this.x=f[0]*i+f[4]*s+f[8]*l+f[12]*c,this.y=f[1]*i+f[5]*s+f[9]*l+f[13]*c,this.z=f[2]*i+f[6]*s+f[10]*l+f[14]*c,this.w=f[3]*i+f[7]*s+f[11]*l+f[15]*c,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);const i=Math.sqrt(1-e.w*e.w);return i<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/i,this.y=e.y/i,this.z=e.z/i),this}setAxisAngleFromRotationMatrix(e){let i,s,l,c;const m=e.elements,h=m[0],y=m[4],S=m[8],_=m[1],b=m[5],T=m[9],C=m[2],v=m[6],x=m[10];if(Math.abs(y-_)<.01&&Math.abs(S-C)<.01&&Math.abs(T-v)<.01){if(Math.abs(y+_)<.1&&Math.abs(S+C)<.1&&Math.abs(T+v)<.1&&Math.abs(h+b+x-3)<.1)return this.set(1,0,0,0),this;i=Math.PI;const P=(h+1)/2,D=(b+1)/2,O=(x+1)/2,U=(y+_)/4,N=(S+C)/4,A=(T+v)/4;return P>D&&P>O?P<.01?(s=0,l=.707106781,c=.707106781):(s=Math.sqrt(P),l=U/s,c=N/s):D>O?D<.01?(s=.707106781,l=0,c=.707106781):(l=Math.sqrt(D),s=U/l,c=A/l):O<.01?(s=.707106781,l=.707106781,c=0):(c=Math.sqrt(O),s=N/c,l=A/c),this.set(s,l,c,i),this}let B=Math.sqrt((v-T)*(v-T)+(S-C)*(S-C)+(_-y)*(_-y));return Math.abs(B)<.001&&(B=1),this.x=(v-T)/B,this.y=(S-C)/B,this.z=(_-y)/B,this.w=Math.acos((h+b+x-1)/2),this}setFromMatrixPosition(e){const i=e.elements;return this.x=i[12],this.y=i[13],this.z=i[14],this.w=i[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,i){return this.x=Pt(this.x,e.x,i.x),this.y=Pt(this.y,e.y,i.y),this.z=Pt(this.z,e.z,i.z),this.w=Pt(this.w,e.w,i.w),this}clampScalar(e,i){return this.x=Pt(this.x,e,i),this.y=Pt(this.y,e,i),this.z=Pt(this.z,e,i),this.w=Pt(this.w,e,i),this}clampLength(e,i){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Pt(s,e,i))}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,i){return this.x+=(e.x-this.x)*i,this.y+=(e.y-this.y)*i,this.z+=(e.z-this.z)*i,this.w+=(e.w-this.w)*i,this}lerpVectors(e,i,s){return this.x=e.x+(i.x-e.x)*s,this.y=e.y+(i.y-e.y)*s,this.z=e.z+(i.z-e.z)*s,this.w=e.w+(i.w-e.w)*s,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,i=0){return this.x=e[i],this.y=e[i+1],this.z=e[i+2],this.w=e[i+3],this}toArray(e=[],i=0){return e[i]=this.x,e[i+1]=this.y,e[i+2]=this.z,e[i+3]=this.w,e}fromBufferAttribute(e,i){return this.x=e.getX(i),this.y=e.getY(i),this.z=e.getZ(i),this.w=e.getW(i),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}};am.prototype.isVector4=!0;let xn=am;class qb extends Rs{constructor(e=1,i=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:$n,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},s),this.isRenderTarget=!0,this.width=e,this.height=i,this.depth=s.depth,this.scissor=new xn(0,0,e,i),this.scissorTest=!1,this.viewport=new xn(0,0,e,i),this.textures=[];const l={width:e,height:i,depth:s.depth},c=new ei(l),f=s.count;for(let p=0;p1);this.dispose()}this.viewport.set(0,0,e,i),this.scissor.set(0,0,e,i)}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 i=0,s=e.textures.length;i>>0}enable(e){this.mask|=1<1){for(let i=0;i1){for(let s=0;s0&&(l.userData=this.userData),l.layers=this.layers.mask,l.matrix=this.matrix.toArray(),l.up=this.up.toArray(),this.pivot!==null&&(l.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(l.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(l.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(l.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(l.type="InstancedMesh",l.count=this.count,l.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(l.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(l.type="BatchedMesh",l.perObjectFrustumCulled=this.perObjectFrustumCulled,l.sortObjects=this.sortObjects,l.drawRanges=this._drawRanges,l.reservedRanges=this._reservedRanges,l.geometryInfo=this._geometryInfo.map(p=>({...p,boundingBox:p.boundingBox?p.boundingBox.toJSON():void 0,boundingSphere:p.boundingSphere?p.boundingSphere.toJSON():void 0})),l.instanceInfo=this._instanceInfo.map(p=>({...p})),l.availableInstanceIds=this._availableInstanceIds.slice(),l.availableGeometryIds=this._availableGeometryIds.slice(),l.nextIndexStart=this._nextIndexStart,l.nextVertexStart=this._nextVertexStart,l.geometryCount=this._geometryCount,l.maxInstanceCount=this._maxInstanceCount,l.maxVertexCount=this._maxVertexCount,l.maxIndexCount=this._maxIndexCount,l.geometryInitialized=this._geometryInitialized,l.matricesTexture=this._matricesTexture.toJSON(e),l.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(l.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(l.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(l.boundingBox=this.boundingBox.toJSON()));function c(p,m){return p[m.uuid]===void 0&&(p[m.uuid]=m.toJSON(e)),m.uuid}if(this.isScene)this.background&&(this.background.isColor?l.background=this.background.toJSON():this.background.isTexture&&(l.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(l.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){l.geometry=c(e.geometries,this.geometry);const p=this.geometry.parameters;if(p!==void 0&&p.shapes!==void 0){const m=p.shapes;if(Array.isArray(m))for(let h=0,y=m.length;h0){l.children=[];for(let p=0;p0){l.animations=[];for(let p=0;p0&&(s.geometries=p),m.length>0&&(s.materials=m),h.length>0&&(s.textures=h),y.length>0&&(s.images=y),S.length>0&&(s.shapes=S),_.length>0&&(s.skeletons=_),b.length>0&&(s.animations=b),T.length>0&&(s.nodes=T)}return s.object=l,s;function f(p){const m=[];for(const h in p){const y=p[h];delete y.metadata,m.push(y)}return m}}clone(e){return new this.constructor().copy(this,e)}copy(e,i=!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.pivot=e.pivot!==null?e.pivot.clone():null,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.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),i===!0)for(let s=0;sb+T?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!h.inputState.pinching&&_<=b-T&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else m!==null&&e.gripSpace&&(c=i.getPose(e.gripSpace,s),c!==null&&(m.matrix.fromArray(c.transform.matrix),m.matrix.decompose(m.position,m.rotation,m.scale),m.matrixWorldNeedsUpdate=!0,c.linearVelocity?(m.hasLinearVelocity=!0,m.linearVelocity.copy(c.linearVelocity)):m.hasLinearVelocity=!1,c.angularVelocity?(m.hasAngularVelocity=!0,m.angularVelocity.copy(c.angularVelocity)):m.hasAngularVelocity=!1,m.eventsEnabled&&m.dispatchEvent({type:"gripUpdated",data:e,target:this})));p!==null&&(l=i.getPose(e.targetRaySpace,s),l===null&&c!==null&&(l=c),l!==null&&(p.matrix.fromArray(l.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,l.linearVelocity?(p.hasLinearVelocity=!0,p.linearVelocity.copy(l.linearVelocity)):p.hasLinearVelocity=!1,l.angularVelocity?(p.hasAngularVelocity=!0,p.angularVelocity.copy(l.angularVelocity)):p.hasAngularVelocity=!1,this.dispatchEvent(tE)))}return p!==null&&(p.visible=l!==null),m!==null&&(m.visible=c!==null),h!==null&&(h.visible=f!==null),this}_getHandJoint(e,i){if(e.joints[i.jointName]===void 0){const s=new jc;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[i.jointName]=s,e.add(s)}return e.joints[i.jointName]}}const jx={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},gs={h:0,s:0,l:0},Xc={h:0,s:0,l:0};function sh(a,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?a+(e-a)*6*i:i<1/2?e:i<2/3?a+(e-a)*6*(2/3-i):a}class dt{constructor(e,i,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,i,s)}set(e,i,s){if(i===void 0&&s===void 0){const l=e;l&&l.isColor?this.copy(l):typeof l=="number"?this.setHex(l):typeof l=="string"&&this.setStyle(l)}else this.setRGB(e,i,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,i=bi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,kt.colorSpaceToWorking(this,i),this}setRGB(e,i,s,l=kt.workingColorSpace){return this.r=e,this.g=i,this.b=s,kt.colorSpaceToWorking(this,l),this}setHSL(e,i,s,l=kt.workingColorSpace){if(e=Gb(e,1),i=Pt(i,0,1),s=Pt(s,0,1),i===0)this.r=this.g=this.b=s;else{const c=s<=.5?s*(1+i):s+i-s*i,f=2*s-c;this.r=sh(f,c,e+1/3),this.g=sh(f,c,e),this.b=sh(f,c,e-1/3)}return kt.colorSpaceToWorking(this,l),this}setStyle(e,i=bi){function s(c){c!==void 0&&parseFloat(c)<1&&_t("Color: Alpha component of "+e+" will be ignored.")}let l;if(l=/^(\w+)\(([^\)]*)\)/.exec(e)){let c;const f=l[1],p=l[2];switch(f){case"rgb":case"rgba":if(c=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(p))return s(c[4]),this.setRGB(Math.min(255,parseInt(c[1],10))/255,Math.min(255,parseInt(c[2],10))/255,Math.min(255,parseInt(c[3],10))/255,i);if(c=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(p))return s(c[4]),this.setRGB(Math.min(100,parseInt(c[1],10))/100,Math.min(100,parseInt(c[2],10))/100,Math.min(100,parseInt(c[3],10))/100,i);break;case"hsl":case"hsla":if(c=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(p))return s(c[4]),this.setHSL(parseFloat(c[1])/360,parseFloat(c[2])/100,parseFloat(c[3])/100,i);break;default:_t("Color: Unknown color model "+e)}}else if(l=/^\#([A-Fa-f\d]+)$/.exec(e)){const c=l[1],f=c.length;if(f===3)return this.setRGB(parseInt(c.charAt(0),16)/15,parseInt(c.charAt(1),16)/15,parseInt(c.charAt(2),16)/15,i);if(f===6)return this.setHex(parseInt(c,16),i);_t("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,i);return this}setColorName(e,i=bi){const s=jx[e.toLowerCase()];return s!==void 0?this.setHex(s,i):_t("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Fa(e.r),this.g=Fa(e.g),this.b=Fa(e.b),this}copyLinearToSRGB(e){return this.r=ro(e.r),this.g=ro(e.g),this.b=ro(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=bi){return kt.workingToColorSpace(Kn.copy(this),e),Math.round(Pt(Kn.r*255,0,255))*65536+Math.round(Pt(Kn.g*255,0,255))*256+Math.round(Pt(Kn.b*255,0,255))}getHexString(e=bi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,i=kt.workingColorSpace){kt.workingToColorSpace(Kn.copy(this),i);const s=Kn.r,l=Kn.g,c=Kn.b,f=Math.max(s,l,c),p=Math.min(s,l,c);let m,h;const y=(p+f)/2;if(p===f)m=0,h=0;else{const S=f-p;switch(h=y<=.5?S/(f+p):S/(2-f-p),f){case s:m=(l-c)/S+(l0&&(i.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(i.object.backgroundIntensity=this.backgroundIntensity),i.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(i.object.environmentIntensity=this.environmentIntensity),i.object.environmentRotation=this.environmentRotation.toArray(),i}}const Xi=new ie,Ra=new ie,rh=new ie,Da=new ie,jr=new ie,Xr=new ie,pv=new ie,oh=new ie,lh=new ie,ch=new ie,uh=new xn,fh=new xn,dh=new xn;class Bi{constructor(e=new ie,i=new ie,s=new ie){this.a=e,this.b=i,this.c=s}static getNormal(e,i,s,l){l.subVectors(s,i),Xi.subVectors(e,i),l.cross(Xi);const c=l.lengthSq();return c>0?l.multiplyScalar(1/Math.sqrt(c)):l.set(0,0,0)}static getBarycoord(e,i,s,l,c){Xi.subVectors(l,i),Ra.subVectors(s,i),rh.subVectors(e,i);const f=Xi.dot(Xi),p=Xi.dot(Ra),m=Xi.dot(rh),h=Ra.dot(Ra),y=Ra.dot(rh),S=f*h-p*p;if(S===0)return c.set(0,0,0),null;const _=1/S,b=(h*m-p*y)*_,T=(f*y-p*m)*_;return c.set(1-b-T,T,b)}static containsPoint(e,i,s,l){return this.getBarycoord(e,i,s,l,Da)===null?!1:Da.x>=0&&Da.y>=0&&Da.x+Da.y<=1}static getInterpolation(e,i,s,l,c,f,p,m){return this.getBarycoord(e,i,s,l,Da)===null?(m.x=0,m.y=0,"z"in m&&(m.z=0),"w"in m&&(m.w=0),null):(m.setScalar(0),m.addScaledVector(c,Da.x),m.addScaledVector(f,Da.y),m.addScaledVector(p,Da.z),m)}static getInterpolatedAttribute(e,i,s,l,c,f){return uh.setScalar(0),fh.setScalar(0),dh.setScalar(0),uh.fromBufferAttribute(e,i),fh.fromBufferAttribute(e,s),dh.fromBufferAttribute(e,l),f.setScalar(0),f.addScaledVector(uh,c.x),f.addScaledVector(fh,c.y),f.addScaledVector(dh,c.z),f}static isFrontFacing(e,i,s,l){return Xi.subVectors(s,i),Ra.subVectors(e,i),Xi.cross(Ra).dot(l)<0}set(e,i,s){return this.a.copy(e),this.b.copy(i),this.c.copy(s),this}setFromPointsAndIndices(e,i,s,l){return this.a.copy(e[i]),this.b.copy(e[s]),this.c.copy(e[l]),this}setFromAttributeAndIndices(e,i,s,l){return this.a.fromBufferAttribute(e,i),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,l),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 Xi.subVectors(this.c,this.b),Ra.subVectors(this.a,this.b),Xi.cross(Ra).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Bi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,i){return Bi.getBarycoord(e,this.a,this.b,this.c,i)}getInterpolation(e,i,s,l,c){return Bi.getInterpolation(e,this.a,this.b,this.c,i,s,l,c)}containsPoint(e){return Bi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Bi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,i){const s=this.a,l=this.b,c=this.c;let f,p;jr.subVectors(l,s),Xr.subVectors(c,s),oh.subVectors(e,s);const m=jr.dot(oh),h=Xr.dot(oh);if(m<=0&&h<=0)return i.copy(s);lh.subVectors(e,l);const y=jr.dot(lh),S=Xr.dot(lh);if(y>=0&&S<=y)return i.copy(l);const _=m*S-y*h;if(_<=0&&m>=0&&y<=0)return f=m/(m-y),i.copy(s).addScaledVector(jr,f);ch.subVectors(e,c);const b=jr.dot(ch),T=Xr.dot(ch);if(T>=0&&b<=T)return i.copy(c);const C=b*h-m*T;if(C<=0&&h>=0&&T<=0)return p=h/(h-T),i.copy(s).addScaledVector(Xr,p);const v=y*T-b*S;if(v<=0&&S-y>=0&&b-T>=0)return pv.subVectors(c,l),p=(S-y)/(S-y+(b-T)),i.copy(l).addScaledVector(pv,p);const x=1/(v+C+_);return f=C*x,p=_*x,i.copy(s).addScaledVector(jr,f).addScaledVector(Xr,p)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class rr{constructor(e=new ie(1/0,1/0,1/0),i=new ie(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=i}set(e,i){return this.min.copy(e),this.max.copy(i),this}setFromArray(e){this.makeEmpty();for(let i=0,s=e.length;i=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,i){return i.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,Wi),Wi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let i,s;return e.normal.x>0?(i=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(i=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(i+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(i+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(i+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(i+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),i<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(fl),qc.subVectors(this.max,fl),Wr.subVectors(e.a,fl),qr.subVectors(e.b,fl),Yr.subVectors(e.c,fl),_s.subVectors(qr,Wr),vs.subVectors(Yr,qr),qs.subVectors(Wr,Yr);let i=[0,-_s.z,_s.y,0,-vs.z,vs.y,0,-qs.z,qs.y,_s.z,0,-_s.x,vs.z,0,-vs.x,qs.z,0,-qs.x,-_s.y,_s.x,0,-vs.y,vs.x,0,-qs.y,qs.x,0];return!hh(i,Wr,qr,Yr,qc)||(i=[1,0,0,0,1,0,0,0,1],!hh(i,Wr,qr,Yr,qc))?!1:(Yc.crossVectors(_s,vs),i=[Yc.x,Yc.y,Yc.z],hh(i,Wr,qr,Yr,qc))}clampPoint(e,i){return i.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Wi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Wi).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:(Na[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Na[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Na[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Na[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Na[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Na[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Na[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Na[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Na),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}}const Na=[new ie,new ie,new ie,new ie,new ie,new ie,new ie,new ie],Wi=new ie,Wc=new rr,Wr=new ie,qr=new ie,Yr=new ie,_s=new ie,vs=new ie,qs=new ie,fl=new ie,qc=new ie,Yc=new ie,Ys=new ie;function hh(a,e,i,s,l){for(let c=0,f=a.length-3;c<=f;c+=3){Ys.fromArray(a,c);const p=l.x*Math.abs(Ys.x)+l.y*Math.abs(Ys.y)+l.z*Math.abs(Ys.z),m=e.dot(Ys),h=i.dot(Ys),y=s.dot(Ys);if(Math.max(-Math.max(m,h,y),Math.min(m,h,y))>p)return!1}return!0}const Rn=new ie,Zc=new bt;let iE=0;class Zi extends Rs{constructor(e,i,s=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:iE++}),this.name="",this.array=e,this.itemSize=i,this.count=e!==void 0?e.length/i:0,this.normalized=s,this.usage=ev,this.updateRanges=[],this.gpuType=qi,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,i){this.updateRanges.push({start:e,count:i})}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,i,s){e*=this.itemSize,s*=i.itemSize;for(let l=0,c=this.itemSize;lthis.radius*this.radius&&(i.sub(this.center).normalize(),i.multiplyScalar(this.radius).add(this.center)),i}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;dl.subVectors(e,this.center);const i=dl.lengthSq();if(i>this.radius*this.radius){const s=Math.sqrt(i),l=(s-this.radius)*.5;this.center.addScaledVector(dl,l/s),this.radius+=l}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):(ph.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(dl.copy(e.center).add(ph)),this.expandByPoint(dl.copy(e.center).sub(ph))),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}}let sE=0;const Oi=new dn,mh=new Ln,Zr=new ie,Mi=new rr,hl=new rr,zn=new ie;class Fi extends Rs{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:sE++}),this.uuid=Nl(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Bb(e)?Wx:Xx)(e,1):this.index=e,this}setIndirect(e,i=0){return this.indirect=e,this.indirectOffset=i,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,i){return this.attributes[e]=i,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,i,s=0){this.groups.push({start:e,count:i,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,i){this.drawRange.start=e,this.drawRange.count=i}applyMatrix4(e){const i=this.attributes.position;i!==void 0&&(i.applyMatrix4(e),i.needsUpdate=!0);const s=this.attributes.normal;if(s!==void 0){const c=new At().getNormalMatrix(e);s.applyNormalMatrix(c),s.needsUpdate=!0}const l=this.attributes.tangent;return l!==void 0&&(l.transformDirection(e),l.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return Oi.makeRotationFromQuaternion(e),this.applyMatrix4(Oi),this}rotateX(e){return Oi.makeRotationX(e),this.applyMatrix4(Oi),this}rotateY(e){return Oi.makeRotationY(e),this.applyMatrix4(Oi),this}rotateZ(e){return Oi.makeRotationZ(e),this.applyMatrix4(Oi),this}translate(e,i,s){return Oi.makeTranslation(e,i,s),this.applyMatrix4(Oi),this}scale(e,i,s){return Oi.makeScale(e,i,s),this.applyMatrix4(Oi),this}lookAt(e){return mh.lookAt(e),mh.updateMatrix(),this.applyMatrix4(mh.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Zr).negate(),this.translate(Zr.x,Zr.y,Zr.z),this}setFromPoints(e){const i=this.getAttribute("position");if(i===void 0){const s=[];for(let l=0,c=e.length;li.count&&_t("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),i.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new rr);const e=this.attributes.position,i=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){jt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new ie(-1/0,-1/0,-1/0),new ie(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),i)for(let s=0,l=i.length;s0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const m=this.parameters;for(const h in m)m[h]!==void 0&&(e[h]=m[h]);return e}e.data={attributes:{}};const i=this.index;i!==null&&(e.data.index={type:i.array.constructor.name,array:Array.prototype.slice.call(i.array)});const s=this.attributes;for(const m in s){const h=s[m];e.data.attributes[m]=h.toJSON(e.data)}const l={};let c=!1;for(const m in this.morphAttributes){const h=this.morphAttributes[m],y=[];for(let S=0,_=h.length;S<_;S++){const b=h[S];y.push(b.toJSON(e.data))}y.length>0&&(l[m]=y,c=!0)}c&&(e.data.morphAttributes=l,e.data.morphTargetsRelative=this.morphTargetsRelative);const f=this.groups;f.length>0&&(e.data.groups=JSON.parse(JSON.stringify(f)));const p=this.boundingSphere;return p!==null&&(e.data.boundingSphere=p.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;const i={};this.name=e.name;const s=e.index;s!==null&&this.setIndex(s.clone());const l=e.attributes;for(const h in l){const y=l[h];this.setAttribute(h,y.clone(i))}const c=e.morphAttributes;for(const h in c){const y=[],S=c[h];for(let _=0,b=S.length;_0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const i in e){const s=e[i];if(s===void 0){_t(`Material: parameter '${i}' has value of undefined.`);continue}const l=this[i];if(l===void 0){_t(`Material: '${i}' is not a property of THREE.${this.type}.`);continue}l&&l.isColor?l.set(s):l&&l.isVector2&&s&&s.isVector2||l&&l.isEuler&&s&&s.isEuler||l&&l.isVector3&&s&&s.isVector3?l.copy(s):this[i]=s}}toJSON(e){const i=e===void 0||typeof e=="string";i&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),this.roughness!==void 0&&(s.roughness=this.roughness),this.metalness!==void 0&&(s.metalness=this.metalness),this.sheen!==void 0&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(s.shininess=this.shininess),this.clearcoat!==void 0&&(s.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(s.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(s.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(s.dispersion=this.dispersion),this.iridescence!==void 0&&(s.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(s.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(s.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(s.combine=this.combine)),this.envMapRotation!==void 0&&(s.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(s.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(s.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(s.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(s.size=this.size),this.shadowSide!==null&&(s.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(s.sizeAttenuation=this.sizeAttenuation),this.blending!==ao&&(s.blending=this.blending),this.side!==Ts&&(s.side=this.side),this.vertexColors===!0&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),this.transparent===!0&&(s.transparent=!0),this.blendSrc!==Oh&&(s.blendSrc=this.blendSrc),this.blendDst!==Ph&&(s.blendDst=this.blendDst),this.blendEquation!==$s&&(s.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(s.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(s.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(s.blendAlpha=this.blendAlpha),this.depthFunc!==uo&&(s.depthFunc=this.depthFunc),this.depthTest===!1&&(s.depthTest=this.depthTest),this.depthWrite===!1&&(s.depthWrite=this.depthWrite),this.colorWrite===!1&&(s.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==J_&&(s.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(s.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==zr&&(s.stencilFail=this.stencilFail),this.stencilZFail!==zr&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==zr&&(s.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(s.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(s.rotation=this.rotation),this.polygonOffset===!0&&(s.polygonOffset=!0),this.polygonOffsetFactor!==0&&(s.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(s.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(s.linewidth=this.linewidth),this.dashSize!==void 0&&(s.dashSize=this.dashSize),this.gapSize!==void 0&&(s.gapSize=this.gapSize),this.scale!==void 0&&(s.scale=this.scale),this.dithering===!0&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),this.alphaHash===!0&&(s.alphaHash=!0),this.alphaToCoverage===!0&&(s.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(s.premultipliedAlpha=!0),this.forceSinglePass===!0&&(s.forceSinglePass=!0),this.allowOverride===!1&&(s.allowOverride=!1),this.wireframe===!0&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(s.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(s.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(s.flatShading=!0),this.visible===!1&&(s.visible=!1),this.toneMapped===!1&&(s.toneMapped=!1),this.fog===!1&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData);function l(c){const f=[];for(const p in c){const m=c[p];delete m.metadata,f.push(m)}return f}if(i){const c=l(e.textures),f=l(e.images);c.length>0&&(s.textures=c),f.length>0&&(s.images=f)}return s}fromJSON(e,i){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new dt().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=i[e.map]||null),e.matcap!==void 0&&(this.matcap=i[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=i[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=i[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=i[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let s=e.normalScale;Array.isArray(s)===!1&&(s=[s,s]),this.normalScale=new bt().fromArray(s)}return e.displacementMap!==void 0&&(this.displacementMap=i[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=i[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=i[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=i[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=i[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=i[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=i[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=i[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=i[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=i[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=i[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=i[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=i[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=i[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new bt().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=i[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=i[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=i[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=i[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=i[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=i[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=i[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const i=e.clippingPlanes;let s=null;if(i!==null){const l=i.length;s=new Array(l);for(let c=0;c!==l;++c)s[c]=i[c].clone()}return this.clippingPlanes=s,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.allowOverride=e.allowOverride,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++}}const Ua=new ie,gh=new ie,Kc=new ie,xs=new ie,_h=new ie,$c=new ie,vh=new ie;class jp{constructor(e=new ie,i=new ie(0,0,-1)){this.origin=e,this.direction=i}set(e,i){return this.origin.copy(e),this.direction.copy(i),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,i){return i.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,Ua)),this}closestPointToPoint(e,i){i.subVectors(e,this.origin);const s=i.dot(this.direction);return s<0?i.copy(this.origin):i.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const i=Ua.subVectors(e,this.origin).dot(this.direction);return i<0?this.origin.distanceToSquared(e):(Ua.copy(this.origin).addScaledVector(this.direction,i),Ua.distanceToSquared(e))}distanceSqToSegment(e,i,s,l){gh.copy(e).add(i).multiplyScalar(.5),Kc.copy(i).sub(e).normalize(),xs.copy(this.origin).sub(gh);const c=e.distanceTo(i)*.5,f=-this.direction.dot(Kc),p=xs.dot(this.direction),m=-xs.dot(Kc),h=xs.lengthSq(),y=Math.abs(1-f*f);let S,_,b,T;if(y>0)if(S=f*m-p,_=f*p-m,T=c*y,S>=0)if(_>=-T)if(_<=T){const C=1/y;S*=C,_*=C,b=S*(S+f*_+2*p)+_*(f*S+_+2*m)+h}else _=c,S=Math.max(0,-(f*_+p)),b=-S*S+_*(_+2*m)+h;else _=-c,S=Math.max(0,-(f*_+p)),b=-S*S+_*(_+2*m)+h;else _<=-T?(S=Math.max(0,-(-f*c+p)),_=S>0?-c:Math.min(Math.max(-c,-m),c),b=-S*S+_*(_+2*m)+h):_<=T?(S=0,_=Math.min(Math.max(-c,-m),c),b=_*(_+2*m)+h):(S=Math.max(0,-(f*c+p)),_=S>0?c:Math.min(Math.max(-c,-m),c),b=-S*S+_*(_+2*m)+h);else _=f>0?-c:c,S=Math.max(0,-(f*_+p)),b=-S*S+_*(_+2*m)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,S),l&&l.copy(gh).addScaledVector(Kc,_),b}intersectSphere(e,i){Ua.subVectors(e.center,this.origin);const s=Ua.dot(this.direction),l=Ua.dot(Ua)-s*s,c=e.radius*e.radius;if(l>c)return null;const f=Math.sqrt(c-l),p=s-f,m=s+f;return m<0?null:p<0?this.at(m,i):this.at(p,i)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const i=e.normal.dot(this.direction);if(i===0)return e.distanceToPoint(this.origin)===0?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/i;return s>=0?s:null}intersectPlane(e,i){const s=this.distanceToPlane(e);return s===null?null:this.at(s,i)}intersectsPlane(e){const i=e.distanceToPoint(this.origin);return i===0||e.normal.dot(this.direction)*i<0}intersectBox(e,i){let s,l,c,f,p,m;const h=1/this.direction.x,y=1/this.direction.y,S=1/this.direction.z,_=this.origin;return h>=0?(s=(e.min.x-_.x)*h,l=(e.max.x-_.x)*h):(s=(e.max.x-_.x)*h,l=(e.min.x-_.x)*h),y>=0?(c=(e.min.y-_.y)*y,f=(e.max.y-_.y)*y):(c=(e.max.y-_.y)*y,f=(e.min.y-_.y)*y),s>f||c>l||((c>s||isNaN(s))&&(s=c),(f=0?(p=(e.min.z-_.z)*S,m=(e.max.z-_.z)*S):(p=(e.max.z-_.z)*S,m=(e.min.z-_.z)*S),s>m||p>l)||((p>s||s!==s)&&(s=p),(m=0?s:l,i)}intersectsBox(e){return this.intersectBox(e,Ua)!==null}intersectTriangle(e,i,s,l,c){_h.subVectors(i,e),$c.subVectors(s,e),vh.crossVectors(_h,$c);let f=this.direction.dot(vh),p;if(f>0){if(l)return null;p=1}else if(f<0)p=-1,f=-f;else return null;xs.subVectors(this.origin,e);const m=p*this.direction.dot($c.crossVectors(xs,$c));if(m<0)return null;const h=p*this.direction.dot(_h.cross(xs));if(h<0||m+h>f)return null;const y=-p*xs.dot(vh);return y<0?null:this.at(y/f,c)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class qx extends vo{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new dt(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 Cs,this.combine=Cx,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}}const mv=new dn,Zs=new jp,Qc=new _o,gv=new ie,Jc=new ie,eu=new ie,tu=new ie,xh=new ie,nu=new ie,_v=new ie,iu=new ie;class Ki extends Ln{constructor(e=new Fi,i=new qx){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=i,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,i){return super.copy(e,i),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(){const i=this.geometry.morphAttributes,s=Object.keys(i);if(s.length>0){const l=i[s[0]];if(l!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let c=0,f=l.length;c(e.far-e.near)**2))&&(mv.copy(c).invert(),Zs.copy(e.ray).applyMatrix4(mv),!(s.boundingBox!==null&&Zs.intersectsBox(s.boundingBox)===!1)&&this._computeIntersections(e,i,Zs)))}_computeIntersections(e,i,s){let l;const c=this.geometry,f=this.material,p=c.index,m=c.attributes.position,h=c.attributes.uv,y=c.attributes.uv1,S=c.attributes.normal,_=c.groups,b=c.drawRange;if(p!==null)if(Array.isArray(f))for(let T=0,C=_.length;Ti.far?null:{distance:h,point:iu.clone(),object:a}}function au(a,e,i,s,l,c,f,p,m,h){a.getVertexPosition(p,Jc),a.getVertexPosition(m,eu),a.getVertexPosition(h,tu);const y=oE(a,e,i,s,Jc,eu,tu,_v);if(y){const S=new ie;Bi.getBarycoord(_v,Jc,eu,tu,S),l&&(y.uv=Bi.getInterpolatedAttribute(l,p,m,h,S,new bt)),c&&(y.uv1=Bi.getInterpolatedAttribute(c,p,m,h,S,new bt)),f&&(y.normal=Bi.getInterpolatedAttribute(f,p,m,h,S,new ie),y.normal.dot(s.direction)>0&&y.normal.multiplyScalar(-1));const _={a:p,b:m,c:h,normal:new ie,materialIndex:0};Bi.getNormal(Jc,eu,tu,_.normal),y.face=_,y.barycoord=S}return y}class Yx extends ei{constructor(e=null,i=1,s=1,l,c,f,p,m,h=Wn,y=Wn,S,_){super(null,f,p,m,h,y,l,c,S,_),this.isDataTexture=!0,this.image={data:e,width:i,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class vv extends Zi{constructor(e,i,s,l=1){super(e,i,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=l}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Kr=new dn,xv=new dn,su=[],yv=new rr,lE=new dn,pl=new Ki,ml=new _o;class cE extends Ki{constructor(e,i,s){super(e,i),this.isInstancedMesh=!0,this.instanceMatrix=new vv(new Float32Array(s*16),16),this.instanceColor=null,this.morphTexture=null,this.count=s,this.boundingBox=null,this.boundingSphere=null;for(let l=0;l1)?null:i.copy(e.start).addScaledVector(l,f)}intersectsLine(e){const i=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return i<0&&s>0||s<0&&i>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,i){const s=i||fE.getNormalMatrix(e),l=this.coplanarPoint(yh).applyMatrix4(e),c=this.normal.applyMatrix3(s).normalize();return this.constant=-l.dot(c),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Ks=new _o,dE=new bt(.5,.5),ru=new ie;class Xp{constructor(e=new Ss,i=new Ss,s=new Ss,l=new Ss,c=new Ss,f=new Ss){this.planes=[e,i,s,l,c,f]}set(e,i,s,l,c,f){const p=this.planes;return p[0].copy(e),p[1].copy(i),p[2].copy(s),p[3].copy(l),p[4].copy(c),p[5].copy(f),this}copy(e){const i=this.planes;for(let s=0;s<6;s++)i[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,i=sa,s=!1){const l=this.planes,c=e.elements,f=c[0],p=c[1],m=c[2],h=c[3],y=c[4],S=c[5],_=c[6],b=c[7],T=c[8],C=c[9],v=c[10],x=c[11],B=c[12],P=c[13],D=c[14],O=c[15];if(l[0].setComponents(h-f,b-y,x-T,O-B).normalize(),l[1].setComponents(h+f,b+y,x+T,O+B).normalize(),l[2].setComponents(h+p,b+S,x+C,O+P).normalize(),l[3].setComponents(h-p,b-S,x-C,O-P).normalize(),s)l[4].setComponents(m,_,v,D).normalize(),l[5].setComponents(h-m,b-_,x-v,O-D).normalize();else if(l[4].setComponents(h-m,b-_,x-v,O-D).normalize(),i===sa)l[5].setComponents(h+m,b+_,x+v,O+D).normalize();else if(i===wl)l[5].setComponents(m,_,v,D).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+i);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ks.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const i=e.geometry;i.boundingSphere===null&&i.computeBoundingSphere(),Ks.copy(i.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ks)}intersectsSprite(e){Ks.center.set(0,0,0);const i=dE.distanceTo(e.center);return Ks.radius=.7071067811865476+i,Ks.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ks)}intersectsSphere(e){const i=this.planes,s=e.center,l=-e.radius;for(let c=0;c<6;c++)if(i[c].distanceToPoint(s)0?e.max.x:e.min.x,ru.y=l.normal.y>0?e.max.y:e.min.y,ru.z=l.normal.z>0?e.max.z:e.min.z,l.distanceToPoint(ru)<0)return!1}return!0}containsPoint(e){const i=this.planes;for(let s=0;s<6;s++)if(i[s].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Wp extends vo{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new dt(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const Ru=new ie,Du=new ie,Sv=new dn,gl=new jp,ou=new _o,Sh=new ie,Mv=new ie;class hE extends Ln{constructor(e=new Fi,i=new Wp){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=i,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,i){return super.copy(e,i),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const i=e.attributes.position,s=[0];for(let l=1,c=i.count;l0){const l=i[s[0]];if(l!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let c=0,f=l.length;cs)return;Sh.applyMatrix4(a.matrixWorld);const h=e.ray.origin.distanceTo(Sh);if(!(he.far))return{distance:h,point:Mv.clone().applyMatrix4(a.matrixWorld),index:f,face:null,faceIndex:null,barycoord:null,object:a}}const bv=new ie,Ev=new ie;class Zx extends hE{constructor(e,i){super(e,i),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const i=e.attributes.position,s=[];for(let l=0,c=i.count;l0?1:-1,y.push(ye.x,ye.y,ye.z),S.push(J/N),S.push(1-xe/A),G+=1}}for(let xe=0;xe0&&(i.defines=this.defines),i.vertexShader=this.vertexShader,i.fragmentShader=this.fragmentShader,i.lights=this.lights,i.clipping=this.clipping;const s={};for(const l in this.extensions)this.extensions[l]===!0&&(s[l]=!0);return Object.keys(s).length>0&&(i.extensions=s),i}fromJSON(e,i){if(super.fromJSON(e,i),e.uniforms!==void 0)for(const s in e.uniforms){const l=e.uniforms[s];switch(this.uniforms[s]={},l.type){case"t":this.uniforms[s].value=i[l.value]||null;break;case"c":this.uniforms[s].value=new dt().setHex(l.value);break;case"v2":this.uniforms[s].value=new bt().fromArray(l.value);break;case"v3":this.uniforms[s].value=new ie().fromArray(l.value);break;case"v4":this.uniforms[s].value=new xn().fromArray(l.value);break;case"m3":this.uniforms[s].value=new At().fromArray(l.value);break;case"m4":this.uniforms[s].value=new dn().fromArray(l.value);break;default:this.uniforms[s].value=l.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(const s in e.extensions)this.extensions[s]=e.extensions[s];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}}class yE extends ca{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class SE extends vo{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new dt(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new dt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Sp,this.normalScale=new bt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Cs,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class ME extends vo{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=wb,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class bE extends vo{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class qp extends Ln{constructor(e,i=1){super(),this.isLight=!0,this.type="Light",this.color=new dt(e),this.intensity=i}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,i){return super.copy(e,i),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const i=super.toJSON(e);return i.object.color=this.color.getHex(),i.object.intensity=this.intensity,i}}class EE extends qp{constructor(e,i,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Ln.DEFAULT_UP),this.updateMatrix(),this.groundColor=new dt(i)}copy(e,i){return super.copy(e,i),this.groundColor.copy(e.groundColor),this}toJSON(e){const i=super.toJSON(e);return i.object.groundColor=this.groundColor.getHex(),i}}const bh=new dn,Av=new ie,Cv=new ie;class TE{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new bt(512,512),this.mapType=Ei,this.map=null,this.mapPass=null,this.matrix=new dn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Xp,this._frameExtents=new bt(1,1),this._viewportCount=1,this._viewports=[new xn(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const i=this.camera,s=this.matrix;Av.setFromMatrixPosition(e.matrixWorld),i.position.copy(Av),Cv.setFromMatrixPosition(e.target.matrixWorld),i.lookAt(Cv),i.updateMatrixWorld(),bh.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(bh,i.coordinateSystem,i.reversedDepth),i.coordinateSystem===wl||i.reversedDepth?s.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(bh)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const du=new ie,hu=new As,na=new ie;class Jx extends Ln{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new dn,this.projectionMatrix=new dn,this.projectionMatrixInverse=new dn,this.coordinateSystem=sa,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,i){return super.copy(e,i),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(du,hu,na),na.x===1&&na.y===1&&na.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(du,hu,na.set(1,1,1)).invert()}updateWorldMatrix(e,i,s=!1){super.updateWorldMatrix(e,i,s),this.matrixWorld.decompose(du,hu,na),na.x===1&&na.y===1&&na.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(du,hu,na.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}const ys=new ie,wv=new bt,Rv=new bt;class Ii extends Jx{constructor(e=50,i=1,s=.1,l=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=l,this.focus=10,this.aspect=i,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,i){return super.copy(e,i),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const i=.5*this.getFilmHeight()/e;this.fov=Mp*2*Math.atan(i),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(El*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Mp*2*Math.atan(Math.tan(El*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,i,s){ys.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(ys.x,ys.y).multiplyScalar(-e/ys.z),ys.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(ys.x,ys.y).multiplyScalar(-e/ys.z)}getViewSize(e,i){return this.getViewBounds(e,wv,Rv),i.subVectors(Rv,wv)}setViewOffset(e,i,s,l,c,f){this.aspect=e/i,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=i,this.view.offsetX=s,this.view.offsetY=l,this.view.width=c,this.view.height=f,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let i=e*Math.tan(El*.5*this.fov)/this.zoom,s=2*i,l=this.aspect*s,c=-.5*l;const f=this.view;if(this.view!==null&&this.view.enabled){const m=f.fullWidth,h=f.fullHeight;c+=f.offsetX*l/m,i-=f.offsetY*s/h,l*=f.width/m,s*=f.height/h}const p=this.filmOffset;p!==0&&(c+=e*p/this.getFilmWidth()),this.projectionMatrix.makePerspective(c,c+l,i,i-s,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const i=super.toJSON(e);return i.object.fov=this.fov,i.object.zoom=this.zoom,i.object.near=this.near,i.object.far=this.far,i.object.focus=this.focus,i.object.aspect=this.aspect,this.view!==null&&(i.object.view=Object.assign({},this.view)),i.object.filmGauge=this.filmGauge,i.object.filmOffset=this.filmOffset,i}}class Yp extends Jx{constructor(e=-1,i=1,s=1,l=-1,c=.1,f=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=i,this.top=s,this.bottom=l,this.near=c,this.far=f,this.updateProjectionMatrix()}copy(e,i){return super.copy(e,i),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,i,s,l,c,f){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=i,this.view.offsetX=s,this.view.offsetY=l,this.view.width=c,this.view.height=f,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),i=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,l=(this.top+this.bottom)/2;let c=s-e,f=s+e,p=l+i,m=l-i;if(this.view!==null&&this.view.enabled){const h=(this.right-this.left)/this.view.fullWidth/this.zoom,y=(this.top-this.bottom)/this.view.fullHeight/this.zoom;c+=h*this.view.offsetX,f=c+h*this.view.width,p-=y*this.view.offsetY,m=p-y*this.view.height}this.projectionMatrix.makeOrthographic(c,f,p,m,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const i=super.toJSON(e);return i.object.zoom=this.zoom,i.object.left=this.left,i.object.right=this.right,i.object.top=this.top,i.object.bottom=this.bottom,i.object.near=this.near,i.object.far=this.far,this.view!==null&&(i.object.view=Object.assign({},this.view)),i}}class AE extends TE{constructor(){super(new Yp(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Dv extends qp{constructor(e,i){super(e,i),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Ln.DEFAULT_UP),this.updateMatrix(),this.target=new Ln,this.shadow=new AE}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const i=super.toJSON(e);return i.object.shadow=this.shadow.toJSON(),i.object.target=this.target.uuid,i}}class CE extends qp{constructor(e,i){super(e,i),this.isAmbientLight=!0,this.type="AmbientLight"}}const $r=-90,Qr=1;class wE extends Ln{constructor(e,i,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const l=new Ii($r,Qr,e,i);l.layers=this.layers,this.add(l);const c=new Ii($r,Qr,e,i);c.layers=this.layers,this.add(c);const f=new Ii($r,Qr,e,i);f.layers=this.layers,this.add(f);const p=new Ii($r,Qr,e,i);p.layers=this.layers,this.add(p);const m=new Ii($r,Qr,e,i);m.layers=this.layers,this.add(m);const h=new Ii($r,Qr,e,i);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,i=this.children.concat(),[s,l,c,f,p,m]=i;for(const h of i)this.remove(h);if(e===sa)s.up.set(0,1,0),s.lookAt(1,0,0),l.up.set(0,1,0),l.lookAt(-1,0,0),c.up.set(0,0,-1),c.lookAt(0,1,0),f.up.set(0,0,1),f.lookAt(0,-1,0),p.up.set(0,1,0),p.lookAt(0,0,1),m.up.set(0,1,0),m.lookAt(0,0,-1);else if(e===wl)s.up.set(0,-1,0),s.lookAt(-1,0,0),l.up.set(0,-1,0),l.lookAt(1,0,0),c.up.set(0,0,1),c.lookAt(0,1,0),f.up.set(0,0,-1),f.lookAt(0,-1,0),p.up.set(0,-1,0),p.lookAt(0,0,1),m.up.set(0,-1,0),m.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const h of i)this.add(h),h.updateMatrixWorld()}update(e,i){this.parent===null&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:l}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[c,f,p,m,h,y]=this.children,S=e.getRenderTarget(),_=e.getActiveCubeFace(),b=e.getActiveMipmapLevel(),T=e.xr.enabled;e.xr.enabled=!1;const C=s.texture.generateMipmaps;s.texture.generateMipmaps=!1;let v=!1;e.isWebGLRenderer===!0?v=e.state.buffers.depth.getReversed():v=e.reversedDepthBuffer,e.setRenderTarget(s,0,l),v&&e.autoClear===!1&&e.clearDepth(),e.render(i,c),e.setRenderTarget(s,1,l),v&&e.autoClear===!1&&e.clearDepth(),e.render(i,f),e.setRenderTarget(s,2,l),v&&e.autoClear===!1&&e.clearDepth(),e.render(i,p),e.setRenderTarget(s,3,l),v&&e.autoClear===!1&&e.clearDepth(),e.render(i,m),e.setRenderTarget(s,4,l),v&&e.autoClear===!1&&e.clearDepth(),e.render(i,h),s.texture.generateMipmaps=C,e.setRenderTarget(s,5,l),v&&e.autoClear===!1&&e.clearDepth(),e.render(i,y),e.setRenderTarget(S,_,b),e.xr.enabled=T,s.texture.needsPMREMUpdate=!0}}class RE extends Ii{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Nv{constructor(e=1,i=0,s=0){this.radius=e,this.phi=i,this.theta=s}set(e,i,s){return this.radius=e,this.phi=i,this.theta=s,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Pt(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,i,s){return this.radius=Math.sqrt(e*e+i*i+s*s),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,s),this.phi=Math.acos(Pt(i/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const sm=class sm{constructor(e,i,s,l){this.elements=[1,0,0,1],e!==void 0&&this.set(e,i,s,l)}identity(){return this.set(1,0,0,1),this}fromArray(e,i=0){for(let s=0;s<4;s++)this.elements[s]=e[s+i];return this}set(e,i,s,l){const c=this.elements;return c[0]=e,c[2]=i,c[1]=s,c[3]=l,this}};sm.prototype.isMatrix2=!0;let Uv=sm;class DE extends Zx{constructor(e=10,i=10,s=4473924,l=8947848){s=new dt(s),l=new dt(l);const c=i/2,f=e/i,p=e/2,m=[],h=[];for(let _=0,b=0,T=-p;_<=i;_++,T+=f){m.push(-p,0,T,p,0,T),m.push(T,0,-p,T,0,p);const C=_===c?s:l;C.toArray(h,b),b+=3,C.toArray(h,b),b+=3,C.toArray(h,b),b+=3,C.toArray(h,b),b+=3}const y=new Fi;y.setAttribute("position",new fi(m,3)),y.setAttribute("color",new fi(h,3));const S=new Wp({vertexColors:!0,toneMapped:!1});super(y,S),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class NE extends Rs{constructor(e,i=null){super(),this.object=e,this.domElement=i,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){_t("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function Lv(a,e,i,s){const l=UE(s);switch(i){case zx:return a*e;case Bp:return a*e/l.components*l.byteLength;case Fp:return a*e/l.components*l.byteLength;case ir:return a*e*2/l.components*l.byteLength;case zp:return a*e*2/l.components*l.byteLength;case Hx:return a*e*3/l.components*l.byteLength;case Yi:return a*e*4/l.components*l.byteLength;case Hp:return a*e*4/l.components*l.byteLength;case vu:case xu:return Math.floor((a+3)/4)*Math.floor((e+3)/4)*8;case yu:case Su:return Math.floor((a+3)/4)*Math.floor((e+3)/4)*16;case Wh:case Yh:return Math.max(a,16)*Math.max(e,8)/4;case Xh:case qh:return Math.max(a,8)*Math.max(e,8)/2;case Zh:case Kh:case Qh:case Jh:return Math.floor((a+3)/4)*Math.floor((e+3)/4)*8;case $h:case Eu:case ep:return Math.floor((a+3)/4)*Math.floor((e+3)/4)*16;case tp:return Math.floor((a+3)/4)*Math.floor((e+3)/4)*16;case np:return Math.floor((a+4)/5)*Math.floor((e+3)/4)*16;case ip:return Math.floor((a+4)/5)*Math.floor((e+4)/5)*16;case ap:return Math.floor((a+5)/6)*Math.floor((e+4)/5)*16;case sp:return Math.floor((a+5)/6)*Math.floor((e+5)/6)*16;case rp:return Math.floor((a+7)/8)*Math.floor((e+4)/5)*16;case op:return Math.floor((a+7)/8)*Math.floor((e+5)/6)*16;case lp:return Math.floor((a+7)/8)*Math.floor((e+7)/8)*16;case cp:return Math.floor((a+9)/10)*Math.floor((e+4)/5)*16;case up:return Math.floor((a+9)/10)*Math.floor((e+5)/6)*16;case fp:return Math.floor((a+9)/10)*Math.floor((e+7)/8)*16;case dp:return Math.floor((a+9)/10)*Math.floor((e+9)/10)*16;case hp:return Math.floor((a+11)/12)*Math.floor((e+9)/10)*16;case pp:return Math.floor((a+11)/12)*Math.floor((e+11)/12)*16;case mp:case gp:case _p:return Math.ceil(a/4)*Math.ceil(e/4)*16;case vp:case xp:return Math.ceil(a/4)*Math.ceil(e/4)*8;case Tu:case yp:return Math.ceil(a/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${i} format.`)}function UE(a){switch(a){case Ei:case Px:return{byteLength:1,components:1};case Al:case Ix:case Ha:return{byteLength:2,components:1};case Pp:case Ip:return{byteLength:2,components:4};case la:case Op:case qi:return{byteLength:4,components:1};case Bx:case Fx:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${a}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Up}}));typeof window<"u"&&(window.__THREE__?_t("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Up);function ey(){let a=null,e=!1,i=null,s=null;function l(c,f){i(c,f),s=a.requestAnimationFrame(l)}return{start:function(){e!==!0&&i!==null&&a!==null&&(s=a.requestAnimationFrame(l),e=!0)},stop:function(){a!==null&&a.cancelAnimationFrame(s),e=!1},setAnimationLoop:function(c){i=c},setContext:function(c){a=c}}}function LE(a){const e=new WeakMap;function i(p,m){const h=p.array,y=p.usage,S=h.byteLength,_=a.createBuffer();a.bindBuffer(m,_),a.bufferData(m,h,y),p.onUploadCallback();let b;if(h instanceof Float32Array)b=a.FLOAT;else if(typeof Float16Array<"u"&&h instanceof Float16Array)b=a.HALF_FLOAT;else if(h instanceof Uint16Array)p.isFloat16BufferAttribute?b=a.HALF_FLOAT:b=a.UNSIGNED_SHORT;else if(h instanceof Int16Array)b=a.SHORT;else if(h instanceof Uint32Array)b=a.UNSIGNED_INT;else if(h instanceof Int32Array)b=a.INT;else if(h instanceof Int8Array)b=a.BYTE;else if(h instanceof Uint8Array)b=a.UNSIGNED_BYTE;else if(h instanceof Uint8ClampedArray)b=a.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+h);return{buffer:_,type:b,bytesPerElement:h.BYTES_PER_ELEMENT,version:p.version,size:S}}function s(p,m,h){const y=m.array,S=m.updateRanges;if(a.bindBuffer(h,p),S.length===0)a.bufferSubData(h,0,y);else{S.sort((b,T)=>b.start-T.start);let _=0;for(let b=1;b 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; float clipOpacity = 1.0; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); if ( clipOpacity == 0.0 ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES float unionClipOpacity = 1.0; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); } #pragma unroll_loop_end clipOpacity *= 1.0 - unionClipOpacity; #endif diffuseColor.a *= clipOpacity; if ( diffuseColor.a == 0.0 ) discard; #else #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif #endif`,KE=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,$E=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,QE=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,JE=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #endif`,eT=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) varying vec4 vColor; #endif`,tT=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec4 vColor; #endif`,nT=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec4( 1.0 ); #endif #ifdef USE_COLOR_ALPHA vColor *= color; #elif defined( USE_COLOR ) vColor.rgb *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.rgb *= instanceColor.rgb; #endif #ifdef USE_BATCHING_COLOR vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); #endif`,iT=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } #define inverseTransformDirection transformDirectionByInverseViewMatrix vec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) { return normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz ); } vec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) { return normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,aT=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,sT=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #endif`,rT=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,oT=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,lT=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`,cT=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,uT="gl_FragColor = linearToOutputTexel( gl_FragColor );",fT=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); }`,dT=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, envMapRotation * reflectVec ); #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif #endif`,hT=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,pT=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,mT=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,gT=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,_T=`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,vT=`#ifdef USE_FOG varying float vFogDepth; #endif`,xT=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,yT=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,ST=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,MT=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,bT=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,ET=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,TT=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif #include `,AT=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); reflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,CT=`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,wT=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,RT=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,DT=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,NT=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb; material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); material.metalness = metalnessFactor; vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = vec3( 0.04 ); material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_DISPERSION material.dispersion = dispersion; #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`,UT=`uniform sampler2D dfgLUT; struct PhysicalMaterial { vec3 diffuseColor; vec3 diffuseContribution; vec3 specularColor; vec3 specularColorBlended; float roughness; float metalness; float specularF90; float dispersion; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; vec3 iridescenceFresnelDielectric; vec3 iridescenceFresnelMetallic; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColorBlended; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float rInv = 1.0 / ( roughness + 0.1 ); float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; float DG = exp( a * dotNV + b ); return saturate( DG ); } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; float Ess_V = dfgV.x + dfgV.y; float Ess_L = dfgL.x + dfgL.y; float Ems_V = 1.0 - Ess_V; float Ems_L = 1.0 - Ess_L; vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); float compensationFactor = Ems_V * Ems_L; vec3 multiScatter = Fms * compensationFactor; return singleScatter + multiScatter; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); #ifdef USE_CLEARCOAT vec3 Ncc = geometryClearcoatNormal; vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); mat3 mInvClearcoat = mat3( vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), vec3( 0, 1, 0 ), vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) ); vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); #endif } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); irradiance *= sheenEnergyComp; #endif reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; diffuse *= sheenEnergyComp; #endif reflectedLight.indirectDiffuse += diffuse; } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; #endif vec3 singleScatteringDielectric = vec3( 0.0 ); vec3 multiScatteringDielectric = vec3( 0.0 ); vec3 singleScatteringMetallic = vec3( 0.0 ); vec3 multiScatteringMetallic = vec3( 0.0 ); #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #endif vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; vec3 indirectSpecular = radiance * singleScattering; indirectSpecular += multiScattering * cosineWeightedIrradiance; vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; indirectSpecular *= sheenEnergyComp; indirectDiffuse *= sheenEnergyComp; #endif reflectedLight.indirectSpecular += indirectSpecular; reflectedLight.indirectDiffuse += indirectDiffuse; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,LT=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #ifdef USE_LIGHT_PROBES_GRID vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz; vec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix ); irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal ); #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,OT=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`,PT=`#if defined( RE_IndirectDiffuse ) #if defined( LAMBERT ) || defined( PHONG ) irradiance += iblIrradiance; #endif RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`,IT=`#ifdef USE_LIGHT_PROBES_GRID uniform highp sampler3D probesSH; uniform vec3 probesMin; uniform vec3 probesMax; uniform vec3 probesResolution; vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { vec3 res = probesResolution; vec3 gridRange = probesMax - probesMin; vec3 resMinusOne = res - 1.0; vec3 probeSpacing = gridRange / resMinusOne; vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5; vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 ); uvw = uvw * resMinusOne / res + 0.5 / res; float nz = res.z; float paddedSlices = nz + 2.0; float atlasDepth = 7.0 * paddedSlices; float uvZBase = uvw.z * nz + 1.0; vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) ); vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) ); vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) ); vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) ); vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) ); vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) ); vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) ); vec3 c0 = s0.xyz; vec3 c1 = vec3( s0.w, s1.xy ); vec3 c2 = vec3( s1.zw, s2.x ); vec3 c3 = s2.yzw; vec3 c4 = s3.xyz; vec3 c5 = vec3( s3.w, s4.xy ); vec3 c6 = vec3( s4.zw, s5.x ); vec3 c7 = s5.yzw; vec3 c8 = s6.xyz; float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z; vec3 result = c0 * 0.886227; result += c1 * 2.0 * 0.511664 * y; result += c2 * 2.0 * 0.511664 * z; result += c3 * 2.0 * 0.511664 * x; result += c4 * 2.0 * 0.429043 * x * y; result += c5 * 2.0 * 0.429043 * y * z; result += c6 * ( 0.743125 * z * z - 0.247708 ); result += c7 * 2.0 * 0.429043 * x * z; result += c8 * 0.429043 * ( x * x - y * y ); return max( result, vec3( 0.0 ) ); } #endif`,BT=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,FT=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,zT=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`,HT=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`,GT=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`,VT=`#ifdef USE_MAP uniform sampler2D map; #endif`,kT=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,jT=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,XT=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,WT=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,qT=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } #endif`,YT=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,ZT=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #endif`,KT=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; #endif uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #endif`,$T=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #endif`,QT=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #ifdef DOUBLE_SIDED tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #ifdef DOUBLE_SIDED tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`,JT=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #if defined( USE_PACKED_NORMALMAP ) mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) ); #endif mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,eA=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,tA=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,nA=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #ifdef FLIP_SIDED vBitangent = - vBitangent; #endif #endif #endif`,iA=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,aA=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,sA=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,rA=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,oA=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,lA=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,cA=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; const float Inv255 = 1. / 255.; const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); vec4 packDepthToRGBA( const in float v ) { if( v <= 0.0 ) return vec4( 0., 0., 0., 0. ); if( v >= 1.0 ) return vec4( 1., 1., 1., 1. ); float vuf; float af = modf( v * PackFactors.a, vuf ); float bf = modf( vuf * ShiftRight8, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); } vec3 packDepthToRGB( const in float v ) { if( v <= 0.0 ) return vec3( 0., 0., 0. ); if( v >= 1.0 ) return vec3( 1., 1., 1. ); float vuf; float bf = modf( v * PackFactors.b, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec3( vuf * Inv255, gf * PackUpscale, bf ); } vec2 packDepthToRG( const in float v ) { if( v <= 0.0 ) return vec2( 0., 0. ); if( v >= 1.0 ) return vec2( 1., 1. ); float vuf; float gf = modf( v * 256., vuf ); return vec2( vuf * Inv255, gf ); } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors4 ); } float unpackRGBToDepth( const in vec3 v ) { return dot( v, UnpackFactors3 ); } float unpackRGToDepth( const in vec2 v ) { return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; } vec4 pack2HalfToRGBA( const in vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( const in vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return depth * ( far - near ) - far; #else return depth * ( near - far ) - near; #endif } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return ( near * far ) / ( ( near - far ) * depth - near ); #else return ( near * far ) / ( ( far - near ) * depth - far ); #endif }`,uA=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,fA=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,dA=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,hA=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,pA=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,mA=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,gA=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #else uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #endif varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #else uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #endif struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #elif defined( SHADOWMAP_TYPE_BASIC ) uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #endif varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #if defined( SHADOWMAP_TYPE_PCF ) float interleavedGradientNoise( vec2 position ) { return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); } vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { const float goldenAngle = 2.399963229728653; float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); float theta = float( sampleIndex ) * goldenAngle + phi; return vec2( cos( theta ), sin( theta ) ) * r; } #endif #if defined( SHADOWMAP_TYPE_PCF ) float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float radius = shadowRadius * texelSize.x; float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; shadow = ( texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_VSM ) float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; float mean = distribution.x; float variance = distribution.y * distribution.y; #ifdef USE_REVERSED_DEPTH_BUFFER float hard_shadow = step( mean, shadowCoord.z ); #else float hard_shadow = step( shadowCoord.z, mean ); #endif if ( hard_shadow == 1.0 ) { shadow = 1.0; } else { variance = max( variance, 0.0000001 ); float d = shadowCoord.z - mean; float p_max = variance / ( variance + d * d ); p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); shadow = max( hard_shadow, p_max ); } } return mix( 1.0, shadow, shadowIntensity ); } #else float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { float depth = texture2D( shadowMap, shadowCoord.xy ).r; #ifdef USE_REVERSED_DEPTH_BUFFER shadow = step( depth, shadowCoord.z ); #else shadow = step( shadowCoord.z, depth ); #endif } return mix( 1.0, shadow, shadowIntensity ); } #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 bd3D = normalize( lightToPosition ); vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { #ifdef USE_REVERSED_DEPTH_BUFFER float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp -= shadowBias; #else float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; #endif float texelSize = shadowRadius / shadowMapSize.x; vec3 absDir = abs( bd3D ); vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); tangent = normalize( cross( bd3D, tangent ) ); vec3 bitangent = cross( bd3D, tangent ); float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; vec2 sample0 = vogelDiskSample( 0, 5, phi ); vec2 sample1 = vogelDiskSample( 1, 5, phi ); vec2 sample2 = vogelDiskSample( 2, 5, phi ); vec2 sample3 = vogelDiskSample( 3, 5, phi ); vec2 sample4 = vogelDiskSample( 4, 5, phi ); shadow = ( texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_BASIC ) float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); float depth = textureCube( shadowMap, bd3D ).r; #ifdef USE_REVERSED_DEPTH_BUFFER depth = 1.0 - depth; #endif shadow = step( dp, depth ); } return mix( 1.0, shadow, shadowIntensity ); } #endif #endif #endif`,_A=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,vA=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) #ifdef HAS_NORMAL vec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix ); #else vec3 shadowWorldNormal = vec3( 0.0 ); #endif vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,xA=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,yA=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,SA=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`,MA=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,bA=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,EA=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,TA=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,AA=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,CA=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 CineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color *= toneMappingExposure; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; color = clamp( color, 0.0, 1.0 ); return color; } vec3 NeutralToneMapping( vec3 color ) { const float StartCompression = 0.8 - 0.04; const float Desaturation = 0.15; color *= toneMappingExposure; float x = min( color.r, min( color.g, color.b ) ); float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; color -= offset; float peak = max( color.r, max( color.g, color.b ) ); if ( peak < StartCompression ) return color; float d = 1. - StartCompression; float newPeak = 1. - d * d / ( peak + d - StartCompression ); color *= newPeak / peak; float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } vec3 CustomToneMapping( vec3 color ) { return color; }`,wA=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = transformNormalByInverseViewMatrix( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,RA=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec4 transmittedLight; vec3 transmittance; #ifdef USE_DISPERSION float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); for ( int i = 0; i < 3; i ++ ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); transmittedLight[ i ] = transmissionSample[ i ]; transmittedLight.a += transmissionSample.a; transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; } transmittedLight.a /= 3.0; #else vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); #endif vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,DA=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,NA=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,UA=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,LA=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`;const OA=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,PA=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,IA=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,BA=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float backgroundBlurriness; uniform float backgroundIntensity; uniform mat3 backgroundRotation; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,FA=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,zA=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,HA=`#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,GA=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { vec4 diffuseColor = vec4( 1.0 ); #include #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include #ifdef USE_REVERSED_DEPTH_BUFFER float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; #else float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; #endif #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #elif DEPTH_PACKING == 3202 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif }`,VA=`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,kA=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); }`,jA=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,XA=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,WA=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include #include }`,qA=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,YA=`#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,ZA=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,KA=`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,$A=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,QA=`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,JA=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,e1=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,t1=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); #include #include #include #include gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,n1=`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,i1=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,a1=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,s1=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_DISPERSION uniform float dispersion; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`,r1=`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,o1=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,l1=`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,c1=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,u1=`#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`,f1=`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include #include }`,d1=`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix[ 3 ]; vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,h1=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`,Dt={alphahash_fragment:OE,alphahash_pars_fragment:PE,alphamap_fragment:IE,alphamap_pars_fragment:BE,alphatest_fragment:FE,alphatest_pars_fragment:zE,aomap_fragment:HE,aomap_pars_fragment:GE,batching_pars_vertex:VE,batching_vertex:kE,begin_vertex:jE,beginnormal_vertex:XE,bsdfs:WE,iridescence_fragment:qE,bumpmap_pars_fragment:YE,clipping_planes_fragment:ZE,clipping_planes_pars_fragment:KE,clipping_planes_pars_vertex:$E,clipping_planes_vertex:QE,color_fragment:JE,color_pars_fragment:eT,color_pars_vertex:tT,color_vertex:nT,common:iT,cube_uv_reflection_fragment:aT,defaultnormal_vertex:sT,displacementmap_pars_vertex:rT,displacementmap_vertex:oT,emissivemap_fragment:lT,emissivemap_pars_fragment:cT,colorspace_fragment:uT,colorspace_pars_fragment:fT,envmap_fragment:dT,envmap_common_pars_fragment:hT,envmap_pars_fragment:pT,envmap_pars_vertex:mT,envmap_physical_pars_fragment:AT,envmap_vertex:gT,fog_vertex:_T,fog_pars_vertex:vT,fog_fragment:xT,fog_pars_fragment:yT,gradientmap_pars_fragment:ST,lightmap_pars_fragment:MT,lights_lambert_fragment:bT,lights_lambert_pars_fragment:ET,lights_pars_begin:TT,lights_toon_fragment:CT,lights_toon_pars_fragment:wT,lights_phong_fragment:RT,lights_phong_pars_fragment:DT,lights_physical_fragment:NT,lights_physical_pars_fragment:UT,lights_fragment_begin:LT,lights_fragment_maps:OT,lights_fragment_end:PT,lightprobes_pars_fragment:IT,logdepthbuf_fragment:BT,logdepthbuf_pars_fragment:FT,logdepthbuf_pars_vertex:zT,logdepthbuf_vertex:HT,map_fragment:GT,map_pars_fragment:VT,map_particle_fragment:kT,map_particle_pars_fragment:jT,metalnessmap_fragment:XT,metalnessmap_pars_fragment:WT,morphinstance_vertex:qT,morphcolor_vertex:YT,morphnormal_vertex:ZT,morphtarget_pars_vertex:KT,morphtarget_vertex:$T,normal_fragment_begin:QT,normal_fragment_maps:JT,normal_pars_fragment:eA,normal_pars_vertex:tA,normal_vertex:nA,normalmap_pars_fragment:iA,clearcoat_normal_fragment_begin:aA,clearcoat_normal_fragment_maps:sA,clearcoat_pars_fragment:rA,iridescence_pars_fragment:oA,opaque_fragment:lA,packing:cA,premultiplied_alpha_fragment:uA,project_vertex:fA,dithering_fragment:dA,dithering_pars_fragment:hA,roughnessmap_fragment:pA,roughnessmap_pars_fragment:mA,shadowmap_pars_fragment:gA,shadowmap_pars_vertex:_A,shadowmap_vertex:vA,shadowmask_pars_fragment:xA,skinbase_vertex:yA,skinning_pars_vertex:SA,skinning_vertex:MA,skinnormal_vertex:bA,specularmap_fragment:EA,specularmap_pars_fragment:TA,tonemapping_fragment:AA,tonemapping_pars_fragment:CA,transmission_fragment:wA,transmission_pars_fragment:RA,uv_pars_fragment:DA,uv_pars_vertex:NA,uv_vertex:UA,worldpos_vertex:LA,background_vert:OA,background_frag:PA,backgroundCube_vert:IA,backgroundCube_frag:BA,cube_vert:FA,cube_frag:zA,depth_vert:HA,depth_frag:GA,distance_vert:VA,distance_frag:kA,equirect_vert:jA,equirect_frag:XA,linedashed_vert:WA,linedashed_frag:qA,meshbasic_vert:YA,meshbasic_frag:ZA,meshlambert_vert:KA,meshlambert_frag:$A,meshmatcap_vert:QA,meshmatcap_frag:JA,meshnormal_vert:e1,meshnormal_frag:t1,meshphong_vert:n1,meshphong_frag:i1,meshphysical_vert:a1,meshphysical_frag:s1,meshtoon_vert:r1,meshtoon_frag:o1,points_vert:l1,points_frag:c1,shadow_vert:u1,shadow_frag:f1,sprite_vert:d1,sprite_frag:h1},We={common:{diffuse:{value:new dt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new At},alphaMap:{value:null},alphaMapTransform:{value:new At},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new At}},envmap:{envMap:{value:null},envMapRotation:{value:new At},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new At}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new At}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new At},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new At},normalScale:{value:new bt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new At},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new At}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new At}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new At}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new dt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new ie},probesMax:{value:new ie},probesResolution:{value:new ie}},points:{diffuse:{value:new dt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new At},alphaTest:{value:0},uvTransform:{value:new At}},sprite:{diffuse:{value:new dt(16777215)},opacity:{value:1},center:{value:new bt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new At},alphaMap:{value:null},alphaMapTransform:{value:new At},alphaTest:{value:0}}},aa={basic:{uniforms:Jn([We.common,We.specularmap,We.envmap,We.aomap,We.lightmap,We.fog]),vertexShader:Dt.meshbasic_vert,fragmentShader:Dt.meshbasic_frag},lambert:{uniforms:Jn([We.common,We.specularmap,We.envmap,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.fog,We.lights,{emissive:{value:new dt(0)},envMapIntensity:{value:1}}]),vertexShader:Dt.meshlambert_vert,fragmentShader:Dt.meshlambert_frag},phong:{uniforms:Jn([We.common,We.specularmap,We.envmap,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.fog,We.lights,{emissive:{value:new dt(0)},specular:{value:new dt(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Dt.meshphong_vert,fragmentShader:Dt.meshphong_frag},standard:{uniforms:Jn([We.common,We.envmap,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.roughnessmap,We.metalnessmap,We.fog,We.lights,{emissive:{value:new dt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Dt.meshphysical_vert,fragmentShader:Dt.meshphysical_frag},toon:{uniforms:Jn([We.common,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.gradientmap,We.fog,We.lights,{emissive:{value:new dt(0)}}]),vertexShader:Dt.meshtoon_vert,fragmentShader:Dt.meshtoon_frag},matcap:{uniforms:Jn([We.common,We.bumpmap,We.normalmap,We.displacementmap,We.fog,{matcap:{value:null}}]),vertexShader:Dt.meshmatcap_vert,fragmentShader:Dt.meshmatcap_frag},points:{uniforms:Jn([We.points,We.fog]),vertexShader:Dt.points_vert,fragmentShader:Dt.points_frag},dashed:{uniforms:Jn([We.common,We.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Dt.linedashed_vert,fragmentShader:Dt.linedashed_frag},depth:{uniforms:Jn([We.common,We.displacementmap]),vertexShader:Dt.depth_vert,fragmentShader:Dt.depth_frag},normal:{uniforms:Jn([We.common,We.bumpmap,We.normalmap,We.displacementmap,{opacity:{value:1}}]),vertexShader:Dt.meshnormal_vert,fragmentShader:Dt.meshnormal_frag},sprite:{uniforms:Jn([We.sprite,We.fog]),vertexShader:Dt.sprite_vert,fragmentShader:Dt.sprite_frag},background:{uniforms:{uvTransform:{value:new At},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Dt.background_vert,fragmentShader:Dt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new At}},vertexShader:Dt.backgroundCube_vert,fragmentShader:Dt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Dt.cube_vert,fragmentShader:Dt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Dt.equirect_vert,fragmentShader:Dt.equirect_frag},distance:{uniforms:Jn([We.common,We.displacementmap,{referencePosition:{value:new ie},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Dt.distance_vert,fragmentShader:Dt.distance_frag},shadow:{uniforms:Jn([We.lights,We.fog,{color:{value:new dt(0)},opacity:{value:1}}]),vertexShader:Dt.shadow_vert,fragmentShader:Dt.shadow_frag}};aa.physical={uniforms:Jn([aa.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new At},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new At},clearcoatNormalScale:{value:new bt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new At},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new At},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new At},sheen:{value:0},sheenColor:{value:new dt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new At},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new At},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new At},transmissionSamplerSize:{value:new bt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new At},attenuationDistance:{value:0},attenuationColor:{value:new dt(0)},specularColor:{value:new dt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new At},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new At},anisotropyVector:{value:new bt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new At}}]),vertexShader:Dt.meshphysical_vert,fragmentShader:Dt.meshphysical_frag};const pu={r:0,b:0,g:0},p1=new dn,ty=new At;ty.set(-1,0,0,0,1,0,0,0,1);function m1(a,e,i,s,l,c){const f=new dt(0);let p=l===!0?0:1,m,h,y=null,S=0,_=null;function b(B){let P=B.isScene===!0?B.background:null;if(P&&P.isTexture){const D=B.backgroundBlurriness>0;P=e.get(P,D)}return P}function T(B){let P=!1;const D=b(B);D===null?v(f,p):D&&D.isColor&&(v(D,1),P=!0);const O=a.xr.getEnvironmentBlendMode();O==="additive"?i.buffers.color.setClear(0,0,0,1,c):O==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,c),(a.autoClear||P)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),a.clear(a.autoClearColor,a.autoClearDepth,a.autoClearStencil))}function C(B,P){const D=b(P);D&&(D.isCubeTexture||D.mapping===Lu)?(h===void 0&&(h=new Ki(new or(1,1,1),new ca({name:"BackgroundCubeMaterial",uniforms:po(aa.backgroundCube.uniforms),vertexShader:aa.backgroundCube.vertexShader,fragmentShader:aa.backgroundCube.fragmentShader,side:ui,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(O,U,N){this.matrixWorld.copyPosition(N.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(h)),h.material.uniforms.envMap.value=D,h.material.uniforms.backgroundBlurriness.value=P.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(p1.makeRotationFromEuler(P.backgroundRotation)).transpose(),D.isCubeTexture&&D.isRenderTargetTexture===!1&&h.material.uniforms.backgroundRotation.value.premultiply(ty),h.material.toneMapped=kt.getTransfer(D.colorSpace)!==an,(y!==D||S!==D.version||_!==a.toneMapping)&&(h.material.needsUpdate=!0,y=D,S=D.version,_=a.toneMapping),h.layers.enableAll(),B.unshift(h,h.geometry,h.material,0,0,null)):D&&D.isTexture&&(m===void 0&&(m=new Ki(new Ou(2,2),new ca({name:"BackgroundMaterial",uniforms:po(aa.background.uniforms),vertexShader:aa.background.vertexShader,fragmentShader:aa.background.fragmentShader,side:Ts,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),m.geometry.deleteAttribute("normal"),Object.defineProperty(m.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(m)),m.material.uniforms.t2D.value=D,m.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,m.material.toneMapped=kt.getTransfer(D.colorSpace)!==an,D.matrixAutoUpdate===!0&&D.updateMatrix(),m.material.uniforms.uvTransform.value.copy(D.matrix),(y!==D||S!==D.version||_!==a.toneMapping)&&(m.material.needsUpdate=!0,y=D,S=D.version,_=a.toneMapping),m.layers.enableAll(),B.unshift(m,m.geometry,m.material,0,0,null))}function v(B,P){B.getRGB(pu,Qx(a)),i.buffers.color.setClear(pu.r,pu.g,pu.b,P,c)}function x(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),m!==void 0&&(m.geometry.dispose(),m.material.dispose(),m=void 0)}return{getClearColor:function(){return f},setClearColor:function(B,P=1){f.set(B),p=P,v(f,p)},getClearAlpha:function(){return p},setClearAlpha:function(B){p=B,v(f,p)},render:T,addToRenderList:C,dispose:x}}function g1(a,e){const i=a.getParameter(a.MAX_VERTEX_ATTRIBS),s={},l=_(null);let c=l,f=!1;function p(V,$,pe,ge,K){let H=!1;const G=S(V,ge,pe,$);c!==G&&(c=G,h(c.object)),H=b(V,ge,pe,K),H&&T(V,ge,pe,K),K!==null&&e.update(K,a.ELEMENT_ARRAY_BUFFER),(H||f)&&(f=!1,D(V,$,pe,ge),K!==null&&a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,e.get(K).buffer))}function m(){return a.createVertexArray()}function h(V){return a.bindVertexArray(V)}function y(V){return a.deleteVertexArray(V)}function S(V,$,pe,ge){const K=ge.wireframe===!0;let H=s[$.id];H===void 0&&(H={},s[$.id]=H);const G=V.isInstancedMesh===!0?V.id:0;let ne=H[G];ne===void 0&&(ne={},H[G]=ne);let ye=ne[pe.id];ye===void 0&&(ye={},ne[pe.id]=ye);let xe=ye[K];return xe===void 0&&(xe=_(m()),ye[K]=xe),xe}function _(V){const $=[],pe=[],ge=[];for(let K=0;K=0){const F=K[ye];let J=H[ye];if(J===void 0&&(ye==="instanceMatrix"&&V.instanceMatrix&&(J=V.instanceMatrix),ye==="instanceColor"&&V.instanceColor&&(J=V.instanceColor)),F===void 0||F.attribute!==J||J&&F.data!==J.data)return!0;G++}return c.attributesNum!==G||c.index!==ge}function T(V,$,pe,ge){const K={},H=$.attributes;let G=0;const ne=pe.getAttributes();for(const ye in ne)if(ne[ye].location>=0){let F=H[ye];F===void 0&&(ye==="instanceMatrix"&&V.instanceMatrix&&(F=V.instanceMatrix),ye==="instanceColor"&&V.instanceColor&&(F=V.instanceColor));const J={};J.attribute=F,F&&F.data&&(J.data=F.data),K[ye]=J,G++}c.attributes=K,c.attributesNum=G,c.index=ge}function C(){const V=c.newAttributes;for(let $=0,pe=V.length;$=0){let xe=K[ne];if(xe===void 0&&(ne==="instanceMatrix"&&V.instanceMatrix&&(xe=V.instanceMatrix),ne==="instanceColor"&&V.instanceColor&&(xe=V.instanceColor)),xe!==void 0){const F=xe.normalized,J=xe.itemSize,Ce=e.get(xe);if(Ce===void 0)continue;const Ue=Ce.buffer,Ie=Ce.type,ae=Ce.bytesPerElement,Ae=Ie===a.INT||Ie===a.UNSIGNED_INT||xe.gpuType===Op;if(xe.isInterleavedBufferAttribute){const Ee=xe.data,He=Ee.stride,nt=xe.offset;if(Ee.isInstancedInterleavedBuffer){for(let Ke=0;Ke0&&a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision>0)return"highp";N="mediump"}return N==="mediump"&&a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision>0&&a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let h=i.precision!==void 0?i.precision:"highp";const y=m(h);y!==h&&(_t("WebGLRenderer:",h,"not supported, using",y,"instead."),h=y);const S=i.logarithmicDepthBuffer===!0,_=i.reversedDepthBuffer===!0&&e.has("EXT_clip_control");i.reversedDepthBuffer===!0&&_===!1&&_t("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");const b=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),T=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),C=a.getParameter(a.MAX_TEXTURE_SIZE),v=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),x=a.getParameter(a.MAX_VERTEX_ATTRIBS),B=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),P=a.getParameter(a.MAX_VARYING_VECTORS),D=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),O=a.getParameter(a.MAX_SAMPLES),U=a.getParameter(a.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:c,getMaxPrecision:m,textureFormatReadable:f,textureTypeReadable:p,precision:h,logarithmicDepthBuffer:S,reversedDepthBuffer:_,maxTextures:b,maxVertexTextures:T,maxTextureSize:C,maxCubemapSize:v,maxAttributes:x,maxVertexUniforms:B,maxVaryings:P,maxFragmentUniforms:D,maxSamples:O,samples:U}}function x1(a){const e=this;let i=null,s=0,l=!1,c=!1;const f=new Ss,p=new At,m={value:null,needsUpdate:!1};this.uniform=m,this.numPlanes=0,this.numIntersection=0,this.init=function(S,_){const b=S.length!==0||_||s!==0||l;return l=_,s=S.length,b},this.beginShadows=function(){c=!0,y(null)},this.endShadows=function(){c=!1},this.setGlobalState=function(S,_){i=y(S,_,0)},this.setState=function(S,_,b){const T=S.clippingPlanes,C=S.clipIntersection,v=S.clipShadows,x=a.get(S);if(!l||T===null||T.length===0||c&&!v)c?y(null):h();else{const B=c?0:s,P=B*4;let D=x.clippingState||null;m.value=D,D=y(T,_,P,b);for(let O=0;O!==P;++O)D[O]=i[O];x.clippingState=D,this.numIntersection=C?this.numPlanes:0,this.numPlanes+=B}};function h(){m.value!==i&&(m.value=i,m.needsUpdate=s>0),e.numPlanes=s,e.numIntersection=0}function y(S,_,b,T){const C=S!==null?S.length:0;let v=null;if(C!==0){if(v=m.value,T!==!0||v===null){const x=b+C*4,B=_.matrixWorldInverse;p.getNormalMatrix(B),(v===null||v.length0&&this._blur(m,0,0,i),this._applyPMREM(m),this._cleanup(m),m}fromEquirectangular(e,i=null){return this._fromTexture(e,i)}fromCubemap(e,i=null){return this._fromTexture(e,i)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=zv(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Fv(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?O:0,O,O),S.setRenderTarget(l),x&&S.render(C,m),S.render(e,m)}S.toneMapping=b,S.autoClear=_,e.background=B}_textureToCubeUV(e,i){const s=this._renderer,l=e.mapping===nr||e.mapping===fo;l?(this._cubemapMaterial===null&&(this._cubemapMaterial=zv()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Fv());const c=l?this._cubemapMaterial:this._equirectMaterial,f=this._lodMeshes[0];f.material=c;const p=c.uniforms;p.envMap.value=e;const m=this._cubeSize;Jr(i,0,0,3*m,2*m),s.setRenderTarget(i),s.render(f,_l)}_applyPMREM(e){const i=this._renderer,s=i.autoClear;i.autoClear=!1;const l=this._lodMeshes.length;for(let c=1;cT-bs?s-T+bs:0),x=4*(this._cubeSize-C);m.envMap.value=e.texture,m.roughness.value=b,m.mipInt.value=T-i,Jr(c,v,x,3*C,2*C),l.setRenderTarget(c),l.render(p,_l),m.envMap.value=c.texture,m.roughness.value=0,m.mipInt.value=T-s,Jr(e,v,x,3*C,2*C),l.setRenderTarget(e),l.render(p,_l)}_blur(e,i,s,l,c){const f=this._pingPongRenderTarget;this._halfBlur(e,f,i,s,l,"latitudinal",c),this._halfBlur(f,e,s,s,l,"longitudinal",c)}_halfBlur(e,i,s,l,c,f,p){const m=this._renderer,h=this._blurMaterial;f!=="latitudinal"&&f!=="longitudinal"&&jt("blur direction must be either latitudinal or longitudinal!");const y=3,S=this._lodMeshes[l];S.material=h;const _=h.uniforms,b=this._sizeLods[s]-1,T=isFinite(c)?Math.PI/(2*b):2*Math.PI/(2*Qs-1),C=c/T,v=isFinite(c)?1+Math.floor(y*C):Qs;v>Qs&&_t(`sigmaRadians, ${c}, is too large and will clip, as it requested ${v} samples when the maximum is set to ${Qs}`);const x=[];let B=0;for(let N=0;NP-bs?l-P+bs:0),U=4*(this._cubeSize-D);Jr(i,O,U,3*D,2*D),m.setRenderTarget(i),m.render(S,_l)}}function M1(a){const e=[],i=[],s=[];let l=a;const c=a-bs+1+Ov.length;for(let f=0;fa-bs?m=Ov[f-a+bs-1]:f===0&&(m=0),i.push(m);const h=1/(p-2),y=-h,S=1+h,_=[y,y,S,y,S,S,y,y,S,S,y,S],b=6,T=6,C=3,v=2,x=1,B=new Float32Array(C*T*b),P=new Float32Array(v*T*b),D=new Float32Array(x*T*b);for(let U=0;U2?0:-1,L=[N,A,0,N+2/3,A,0,N+2/3,A+1,0,N,A,0,N+2/3,A+1,0,N,A+1,0];B.set(L,C*T*U),P.set(_,v*T*U);const j=[U,U,U,U,U,U];D.set(j,x*T*U)}const O=new Fi;O.setAttribute("position",new Zi(B,C)),O.setAttribute("uv",new Zi(P,v)),O.setAttribute("faceIndex",new Zi(D,x)),s.push(new Ki(O,null)),l>bs&&l--}return{lodMeshes:s,sizeLods:e,sigmas:i}}function Bv(a,e,i){const s=new oa(a,e,i);return s.texture.mapping=Lu,s.texture.name="PMREM.cubeUv",s.scissorTest=!0,s}function Jr(a,e,i,s,l){a.viewport.set(e,i,s,l),a.scissor.set(e,i,s,l)}function b1(a,e,i){return new ca({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:y1,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/i,CUBEUV_MAX_MIP:`${a}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Pu(),fragmentShader:` precision highp float; precision highp int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform float roughness; uniform float mipInt; #define ENVMAP_TYPE_CUBE_UV #include #define PI 3.14159265359 // Van der Corput radical inverse float radicalInverse_VdC(uint bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; // / 0x100000000 } // Hammersley sequence vec2 hammersley(uint i, uint N) { return vec2(float(i) / float(N), radicalInverse_VdC(i)); } // GGX VNDF importance sampling (Eric Heitz 2018) // "Sampling the GGX Distribution of Visible Normals" // https://jcgt.org/published/0007/04/01/ vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { float alpha = roughness * roughness; // Section 4.1: Orthonormal basis vec3 T1 = vec3(1.0, 0.0, 0.0); vec3 T2 = cross(V, T1); // Section 4.2: Parameterization of projected area float r = sqrt(Xi.x); float phi = 2.0 * PI * Xi.y; float t1 = r * cos(phi); float t2 = r * sin(phi); float s = 0.5 * (1.0 + V.z); t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; // Section 4.3: Reprojection onto hemisphere vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; // Section 3.4: Transform back to ellipsoid configuration return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); } void main() { vec3 N = normalize(vOutputDirection); vec3 V = N; // Assume view direction equals normal for pre-filtering vec3 prefilteredColor = vec3(0.0); float totalWeight = 0.0; // For very low roughness, just sample the environment directly if (roughness < 0.001) { gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); return; } // Tangent space basis for VNDF sampling vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 tangent = normalize(cross(up, N)); vec3 bitangent = cross(N, tangent); for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); // For PMREM, V = N, so in tangent space V is always (0, 0, 1) vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); // Transform H back to world space vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); vec3 L = normalize(2.0 * dot(V, H) * H - V); float NdotL = max(dot(N, L), 0.0); if(NdotL > 0.0) { // Sample environment at fixed mip level // VNDF importance sampling handles the distribution filtering vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); // Weight by NdotL for the split-sum approximation // VNDF PDF naturally accounts for the visible microfacet distribution prefilteredColor += sampleColor * NdotL; totalWeight += NdotL; } } if (totalWeight > 0.0) { prefilteredColor = prefilteredColor / totalWeight; } gl_FragColor = vec4(prefilteredColor, 1.0); } `,blending:Ba,depthTest:!1,depthWrite:!1})}function E1(a,e,i){const s=new Float32Array(Qs),l=new ie(0,1,0);return new ca({name:"SphericalGaussianBlur",defines:{n:Qs,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/i,CUBEUV_MAX_MIP:`${a}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:s},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:l}},vertexShader:Pu(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:Ba,depthTest:!1,depthWrite:!1})}function Fv(){return new ca({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Pu(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:Ba,depthTest:!1,depthWrite:!1})}function zv(){return new ca({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Pu(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:Ba,depthTest:!1,depthWrite:!1})}function Pu(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}class ny extends oa{constructor(e=1,i={}){super(e,e,i),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},l=[s,s,s,s,s,s];this.texture=new Kx(l),this._setTextureOptions(i),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,i){this.texture.type=i.type,this.texture.colorSpace=i.colorSpace,this.texture.generateMipmaps=i.generateMipmaps,this.texture.minFilter=i.minFilter,this.texture.magFilter=i.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},l=new or(5,5,5),c=new ca({name:"CubemapFromEquirect",uniforms:po(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:ui,blending:Ba});c.uniforms.tEquirect.value=i;const f=new Ki(l,c),p=i.minFilter;return i.minFilter===Js&&(i.minFilter=$n),new wE(1,10,this).update(e,f),i.minFilter=p,f.geometry.dispose(),f.material.dispose(),this}clear(e,i=!0,s=!0,l=!0){const c=e.getRenderTarget();for(let f=0;f<6;f++)e.setRenderTarget(this,f),e.clear(i,s,l);e.setRenderTarget(c)}}function T1(a){let e=new WeakMap,i=new WeakMap,s=null;function l(_,b=!1){return _==null?null:b?f(_):c(_)}function c(_){if(_&&_.isTexture){const b=_.mapping;if(b===Zd||b===Kd)if(e.has(_)){const T=e.get(_).texture;return p(T,_.mapping)}else{const T=_.image;if(T&&T.height>0){const C=new ny(T.height);return C.fromEquirectangularTexture(a,_),e.set(_,C),_.addEventListener("dispose",h),p(C.texture,_.mapping)}else return null}}return _}function f(_){if(_&&_.isTexture){const b=_.mapping,T=b===Zd||b===Kd,C=b===nr||b===fo;if(T||C){let v=i.get(_);const x=v!==void 0?v.texture.pmremVersion:0;if(_.isRenderTargetTexture&&_.pmremVersion!==x)return s===null&&(s=new Iv(a)),v=T?s.fromEquirectangular(_,v):s.fromCubemap(_,v),v.texture.pmremVersion=_.pmremVersion,i.set(_,v),v.texture;if(v!==void 0)return v.texture;{const B=_.image;return T&&B&&B.height>0||C&&B&&m(B)?(s===null&&(s=new Iv(a)),v=T?s.fromEquirectangular(_):s.fromCubemap(_),v.texture.pmremVersion=_.pmremVersion,i.set(_,v),_.addEventListener("dispose",y),v.texture):null}}}return _}function p(_,b){return b===Zd?_.mapping=nr:b===Kd&&(_.mapping=fo),_}function m(_){let b=0;const T=6;for(let C=0;C=65535?Wx:Xx)(_,1);v.version=C;const x=c.get(S);x&&e.remove(x),c.set(S,v)}function y(S){const _=c.get(S);if(_){const b=S.index;b!==null&&_.versione.maxTextureSize&&(U=Math.ceil(O/e.maxTextureSize),O=e.maxTextureSize);const N=new Float32Array(O*U*4*S),A=new Vx(N,O,U,S);A.type=qi,A.needsUpdate=!0;const L=D*4;for(let V=0;V #include void main() { gl_FragColor = texture2D( tDiffuse, vUv ); #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #elif defined( CUSTOM_TONE_MAPPING ) gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); #endif #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }`,depthTest:!1,depthWrite:!1}),y=new Ki(m,h),S=new Yp(-1,1,1,-1,0,1);let _=null,b=null,T=!1,C,v=null,x=[],B=!1;this.setSize=function(P,D){f.setSize(P,D),p.setSize(P,D);for(let O=0;O0&&x[0].isRenderPass===!0;const D=f.width,O=f.height;for(let U=0;U0)return a;const l=e*i;let c=Hv[l];if(c===void 0&&(c=new Float32Array(l),Hv[l]=c),e!==0){s.toArray(c,0);for(let f=1,p=0;f!==e;++f)p+=i,a[f].toArray(c,p)}return c}function On(a,e){if(a.length!==e.length)return!1;for(let i=0,s=a.length;i0&&(this.seq=l.concat(c))}setValue(e,i,s,l){const c=this.map[i];c!==void 0&&c.setValue(e,s,l)}setOptional(e,i,s){const l=i[s];l!==void 0&&this.setValue(e,s,l)}static upload(e,i,s,l){for(let c=0,f=i.length;c!==f;++c){const p=i[c],m=s[p.id];m.needsUpdate!==!1&&p.setValue(e,m.value,l)}}static seqWithValue(e,i){const s=[];for(let l=0,c=e.length;l!==c;++l){const f=e[l];f.id in i&&s.push(f)}return s}}function Wv(a,e,i){const s=a.createShader(e);return a.shaderSource(s,i),a.compileShader(s),s}const EC=37297;let TC=0;function AC(a,e){const i=a.split(` `),s=[],l=Math.max(e-6,0),c=Math.min(e+6,i.length);for(let f=l;f":" "} ${p}: ${i[f]}`)}return s.join(` `)}const qv=new At;function CC(a){kt._getMatrix(qv,kt.workingColorSpace,a);const e=`mat3( ${qv.elements.map(i=>i.toFixed(4))} )`;switch(kt.getTransfer(a)){case Cu:return[e,"LinearTransferOETF"];case an:return[e,"sRGBTransferOETF"];default:return _t("WebGLProgram: Unsupported color space: ",a),[e,"LinearTransferOETF"]}}function Yv(a,e,i){const s=a.getShaderParameter(e,a.COMPILE_STATUS),c=(a.getShaderInfoLog(e)||"").trim();if(s&&c==="")return"";const f=/ERROR: 0:(\d+)/.exec(c);if(f){const p=parseInt(f[1]);return i.toUpperCase()+` `+c+` `+AC(a.getShaderSource(e),p)}else return c}function wC(a,e){const i=CC(e);return[`vec4 ${a}( vec4 value ) {`,` return ${i[1]}( vec4( value.rgb * ${i[0]}, value.a ) );`,"}"].join(` `)}const RC={[wx]:"Linear",[Rx]:"Reinhard",[Dx]:"Cineon",[Lp]:"ACESFilmic",[Ux]:"AgX",[Lx]:"Neutral",[Nx]:"Custom"};function DC(a,e){const i=RC[e];return i===void 0?(_t("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+a+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+a+"( vec3 color ) { return "+i+"ToneMapping( color ); }"}const mu=new ie;function NC(){kt.getLuminanceCoefficients(mu);const a=mu.x.toFixed(4),e=mu.y.toFixed(4),i=mu.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${a}, ${e}, ${i} );`," return dot( weights, rgb );","}"].join(` `)}function UC(a){return[a.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",a.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(yl).join(` `)}function LC(a){const e=[];for(const i in a){const s=a[i];s!==!1&&e.push("#define "+i+" "+s)}return e.join(` `)}function OC(a,e){const i={},s=a.getProgramParameter(e,a.ACTIVE_ATTRIBUTES);for(let l=0;l/gm;function Ep(a){return a.replace(PC,BC)}const IC=new Map;function BC(a,e){let i=Dt[e];if(i===void 0){const s=IC.get(e);if(s!==void 0)i=Dt[s],_t('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,s);else throw new Error("THREE.WebGLProgram: Can not resolve #include <"+e+">")}return Ep(i)}const FC=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function $v(a){return a.replace(FC,zC)}function zC(a,e,i,s){let l="";for(let c=parseInt(e);c0&&(v+=` `),x=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,T].filter(yl).join(` `),x.length>0&&(x+=` `)):(v=[Qv(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,T,i.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",i.batching?"#define USE_BATCHING":"",i.batchingColor?"#define USE_BATCHING_COLOR":"",i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.instancingMorph?"#define USE_INSTANCING_MORPH":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+y:"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.displacementMap?"#define USE_DISPLACEMENTMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.mapUv?"#define MAP_UV "+i.mapUv:"",i.alphaMapUv?"#define ALPHAMAP_UV "+i.alphaMapUv:"",i.lightMapUv?"#define LIGHTMAP_UV "+i.lightMapUv:"",i.aoMapUv?"#define AOMAP_UV "+i.aoMapUv:"",i.emissiveMapUv?"#define EMISSIVEMAP_UV "+i.emissiveMapUv:"",i.bumpMapUv?"#define BUMPMAP_UV "+i.bumpMapUv:"",i.normalMapUv?"#define NORMALMAP_UV "+i.normalMapUv:"",i.displacementMapUv?"#define DISPLACEMENTMAP_UV "+i.displacementMapUv:"",i.metalnessMapUv?"#define METALNESSMAP_UV "+i.metalnessMapUv:"",i.roughnessMapUv?"#define ROUGHNESSMAP_UV "+i.roughnessMapUv:"",i.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+i.anisotropyMapUv:"",i.clearcoatMapUv?"#define CLEARCOATMAP_UV "+i.clearcoatMapUv:"",i.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+i.clearcoatNormalMapUv:"",i.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+i.clearcoatRoughnessMapUv:"",i.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+i.iridescenceMapUv:"",i.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+i.iridescenceThicknessMapUv:"",i.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+i.sheenColorMapUv:"",i.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+i.sheenRoughnessMapUv:"",i.specularMapUv?"#define SPECULARMAP_UV "+i.specularMapUv:"",i.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+i.specularColorMapUv:"",i.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+i.specularIntensityMapUv:"",i.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+i.transmissionMapUv:"",i.thicknessMapUv?"#define THICKNESSMAP_UV "+i.thicknessMapUv:"",i.vertexTangents&&i.flatShading===!1?"#define USE_TANGENT":"",i.vertexNormals?"#define HAS_NORMAL":"",i.vertexColors?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.flatShading?"#define FLAT_SHADED":"",i.skinning?"#define USE_SKINNING":"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals&&i.flatShading===!1?"#define USE_MORPHNORMALS":"",i.morphColors?"#define USE_MORPHCOLORS":"",i.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+i.morphTextureStride:"",i.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+i.morphTargetsCount:"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+m:"",i.sizeAttenuation?"#define USE_SIZEATTENUATION":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",i.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` `].filter(yl).join(` `),x=[Qv(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,T,i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",i.map?"#define USE_MAP":"",i.matcap?"#define USE_MATCAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+h:"",i.envMap?"#define "+y:"",i.envMap?"#define "+S:"",_?"#define CUBEUV_TEXEL_WIDTH "+_.texelWidth:"",_?"#define CUBEUV_TEXEL_HEIGHT "+_.texelHeight:"",_?"#define CUBEUV_MAX_MIP "+_.maxMip+".0":"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoat?"#define USE_CLEARCOAT":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.dispersion?"#define USE_DISPERSION":"",i.iridescence?"#define USE_IRIDESCENCE":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaTest?"#define USE_ALPHATEST":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.sheen?"#define USE_SHEEN":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.vertexTangents&&i.flatShading===!1?"#define USE_TANGENT":"",i.vertexColors||i.instancingColor?"#define USE_COLOR":"",i.vertexAlphas||i.batchingColor?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.gradientMap?"#define USE_GRADIENTMAP":"",i.flatShading?"#define FLAT_SHADED":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+m:"",i.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",i.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",i.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",i.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",i.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",i.toneMapping!==ra?"#define TONE_MAPPING":"",i.toneMapping!==ra?Dt.tonemapping_pars_fragment:"",i.toneMapping!==ra?DC("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",Dt.colorspace_pars_fragment,wC("linearToOutputTexel",i.outputColorSpace),NC(),i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"",` `].filter(yl).join(` `)),f=Ep(f),f=Zv(f,i),f=Kv(f,i),p=Ep(p),p=Zv(p,i),p=Kv(p,i),f=$v(f),p=$v(p),i.isRawShaderMaterial!==!0&&(B=`#version 300 es `,v=[b,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+v,x=["#define varying in",i.glslVersion===tv?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===tv?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` `+x);const P=B+v+f,D=B+x+p,O=Wv(l,l.VERTEX_SHADER,P),U=Wv(l,l.FRAGMENT_SHADER,D);l.attachShader(C,O),l.attachShader(C,U),i.index0AttributeName!==void 0?l.bindAttribLocation(C,0,i.index0AttributeName):i.hasPositionAttribute===!0&&l.bindAttribLocation(C,0,"position"),l.linkProgram(C);function N(V){if(a.debug.checkShaderErrors){const $=l.getProgramInfoLog(C)||"",pe=l.getShaderInfoLog(O)||"",ge=l.getShaderInfoLog(U)||"",K=$.trim(),H=pe.trim(),G=ge.trim();let ne=!0,ye=!0;if(l.getProgramParameter(C,l.LINK_STATUS)===!1)if(ne=!1,typeof a.debug.onShaderError=="function")a.debug.onShaderError(l,C,O,U);else{const xe=Yv(l,O,"vertex"),F=Yv(l,U,"fragment");jt("WebGLProgram: Shader Error "+l.getError()+" - VALIDATE_STATUS "+l.getProgramParameter(C,l.VALIDATE_STATUS)+` Material Name: `+V.name+` Material Type: `+V.type+` Program Info Log: `+K+` `+xe+` `+F)}else K!==""?_t("WebGLProgram: Program Info Log:",K):(H===""||G==="")&&(ye=!1);ye&&(V.diagnostics={runnable:ne,programLog:K,vertexShader:{log:H,prefix:v},fragmentShader:{log:G,prefix:x}})}l.deleteShader(O),l.deleteShader(U),A=new Mu(l,C),L=OC(l,C)}let A;this.getUniforms=function(){return A===void 0&&N(this),A};let L;this.getAttributes=function(){return L===void 0&&N(this),L};let j=i.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return j===!1&&(j=l.getProgramParameter(C,EC)),j},this.destroy=function(){s.releaseStatesOfProgram(this),l.deleteProgram(C),this.program=void 0},this.type=i.shaderType,this.name=i.shaderName,this.id=TC++,this.cacheKey=e,this.usedTimes=1,this.program=C,this.vertexShader=O,this.fragmentShader=U,this}let KC=0;class $C{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,i,s){const l=this._getShaderCacheForMaterial(e);return l.has(i)===!1&&(l.add(i),i.usedTimes++),l.has(s)===!1&&(l.add(s),s.usedTimes++),this}remove(e){const i=this.materialCache.get(e);for(const s of i)s.usedTimes--,s.usedTimes===0&&this.shaderCache.delete(s.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const i=this.materialCache;let s=i.get(e);return s===void 0&&(s=new Set,i.set(e,s)),s}_getShaderStage(e){const i=this.shaderCache;let s=i.get(e);return s===void 0&&(s=new QC(e),i.set(e,s)),s}}class QC{constructor(e){this.id=KC++,this.code=e,this.usedTimes=0}}function JC(a){return a===ir||a===Eu||a===Tu}function ew(a,e,i,s,l,c){const f=new kx,p=new $C,m=new Set,h=[],y=new Map,S=s.logarithmicDepthBuffer;let _=s.precision;const b={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function T(A){return m.add(A),A===0?"uv":`uv${A}`}function C(A,L,j,V,$,pe){const ge=V.fog,K=$.geometry,H=A.isMeshStandardMaterial||A.isMeshLambertMaterial||A.isMeshPhongMaterial?V.environment:null,G=A.isMeshStandardMaterial||A.isMeshLambertMaterial&&!A.envMap||A.isMeshPhongMaterial&&!A.envMap,ne=e.get(A.envMap||H,G),ye=ne&&ne.mapping===Lu?ne.image.height:null,xe=b[A.type];A.precision!==null&&(_=s.getMaxPrecision(A.precision),_!==A.precision&&_t("WebGLProgram.getParameters:",A.precision,"not supported, using",_,"instead."));const F=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,J=F!==void 0?F.length:0;let Ce=0;K.morphAttributes.position!==void 0&&(Ce=1),K.morphAttributes.normal!==void 0&&(Ce=2),K.morphAttributes.color!==void 0&&(Ce=3);let Ue,Ie,ae,Ae;if(xe){const De=aa[xe];Ue=De.vertexShader,Ie=De.fragmentShader}else{Ue=A.vertexShader,Ie=A.fragmentShader;const De=p.getVertexShaderStage(A),ft=p.getFragmentShaderStage(A);p.update(A,De,ft),ae=De.id,Ae=ft.id}const Ee=a.getRenderTarget(),He=a.state.buffers.depth.getReversed(),nt=$.isInstancedMesh===!0,Ke=$.isBatchedMesh===!0,zt=!!A.map,ht=!!A.matcap,Et=!!ne,yt=!!A.aoMap,St=!!A.lightMap,Mt=!!A.bumpMap&&A.wireframe===!1,Ht=!!A.normalMap,Gt=!!A.displacementMap,st=!!A.emissiveMap,It=!!A.metalnessMap,W=!!A.roughnessMap,z=A.anisotropy>0,Ye=A.clearcoat>0,xt=A.dispersion>0,I=A.iridescence>0,E=A.sheen>0,X=A.transmission>0,se=z&&!!A.anisotropyMap,me=Ye&&!!A.clearcoatMap,Ne=Ye&&!!A.clearcoatNormalMap,Oe=Ye&&!!A.clearcoatRoughnessMap,_e=I&&!!A.iridescenceMap,he=I&&!!A.iridescenceThicknessMap,Le=E&&!!A.sheenColorMap,je=E&&!!A.sheenRoughnessMap,ze=!!A.specularMap,Fe=!!A.specularColorMap,Qe=!!A.specularIntensityMap,Je=X&&!!A.transmissionMap,pt=X&&!!A.thicknessMap,Z=!!A.gradientMap,Pe=!!A.alphaMap,Se=A.alphaTest>0,Be=!!A.alphaHash,ke=!!A.extensions;let q=ra;A.toneMapped&&(Ee===null||Ee.isXRRenderTarget===!0)&&(q=a.toneMapping);const Me={shaderID:xe,shaderType:A.type,shaderName:A.name,vertexShader:Ue,fragmentShader:Ie,defines:A.defines,customVertexShaderID:ae,customFragmentShaderID:Ae,isRawShaderMaterial:A.isRawShaderMaterial===!0,glslVersion:A.glslVersion,precision:_,batching:Ke,batchingColor:Ke&&$._colorsTexture!==null,instancing:nt,instancingColor:nt&&$.instanceColor!==null,instancingMorph:nt&&$.morphTexture!==null,outputColorSpace:Ee===null?a.outputColorSpace:Ee.isXRRenderTarget===!0?Ee.texture.colorSpace:kt.workingColorSpace,alphaToCoverage:!!A.alphaToCoverage,map:zt,matcap:ht,envMap:Et,envMapMode:Et&&ne.mapping,envMapCubeUVHeight:ye,aoMap:yt,lightMap:St,bumpMap:Mt,normalMap:Ht,displacementMap:Gt,emissiveMap:st,normalMapObjectSpace:Ht&&A.normalMapType===Rb,normalMapTangentSpace:Ht&&A.normalMapType===Sp,packedNormalMap:Ht&&A.normalMapType===Sp&&JC(A.normalMap.format),metalnessMap:It,roughnessMap:W,anisotropy:z,anisotropyMap:se,clearcoat:Ye,clearcoatMap:me,clearcoatNormalMap:Ne,clearcoatRoughnessMap:Oe,dispersion:xt,iridescence:I,iridescenceMap:_e,iridescenceThicknessMap:he,sheen:E,sheenColorMap:Le,sheenRoughnessMap:je,specularMap:ze,specularColorMap:Fe,specularIntensityMap:Qe,transmission:X,transmissionMap:Je,thicknessMap:pt,gradientMap:Z,opaque:A.transparent===!1&&A.blending===ao&&A.alphaToCoverage===!1,alphaMap:Pe,alphaTest:Se,alphaHash:Be,combine:A.combine,mapUv:zt&&T(A.map.channel),aoMapUv:yt&&T(A.aoMap.channel),lightMapUv:St&&T(A.lightMap.channel),bumpMapUv:Mt&&T(A.bumpMap.channel),normalMapUv:Ht&&T(A.normalMap.channel),displacementMapUv:Gt&&T(A.displacementMap.channel),emissiveMapUv:st&&T(A.emissiveMap.channel),metalnessMapUv:It&&T(A.metalnessMap.channel),roughnessMapUv:W&&T(A.roughnessMap.channel),anisotropyMapUv:se&&T(A.anisotropyMap.channel),clearcoatMapUv:me&&T(A.clearcoatMap.channel),clearcoatNormalMapUv:Ne&&T(A.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Oe&&T(A.clearcoatRoughnessMap.channel),iridescenceMapUv:_e&&T(A.iridescenceMap.channel),iridescenceThicknessMapUv:he&&T(A.iridescenceThicknessMap.channel),sheenColorMapUv:Le&&T(A.sheenColorMap.channel),sheenRoughnessMapUv:je&&T(A.sheenRoughnessMap.channel),specularMapUv:ze&&T(A.specularMap.channel),specularColorMapUv:Fe&&T(A.specularColorMap.channel),specularIntensityMapUv:Qe&&T(A.specularIntensityMap.channel),transmissionMapUv:Je&&T(A.transmissionMap.channel),thicknessMapUv:pt&&T(A.thicknessMap.channel),alphaMapUv:Pe&&T(A.alphaMap.channel),vertexTangents:!!K.attributes.tangent&&(Ht||z),vertexNormals:!!K.attributes.normal,vertexColors:A.vertexColors,vertexAlphas:A.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,pointsUvs:$.isPoints===!0&&!!K.attributes.uv&&(zt||Pe),fog:!!ge,useFog:A.fog===!0,fogExp2:!!ge&&ge.isFogExp2,flatShading:A.wireframe===!1&&(A.flatShading===!0||K.attributes.normal===void 0&&Ht===!1&&(A.isMeshLambertMaterial||A.isMeshPhongMaterial||A.isMeshStandardMaterial||A.isMeshPhysicalMaterial)),sizeAttenuation:A.sizeAttenuation===!0,logarithmicDepthBuffer:S,reversedDepthBuffer:He,skinning:$.isSkinnedMesh===!0,hasPositionAttribute:K.attributes.position!==void 0,morphTargets:K.morphAttributes.position!==void 0,morphNormals:K.morphAttributes.normal!==void 0,morphColors:K.morphAttributes.color!==void 0,morphTargetsCount:J,morphTextureStride:Ce,numDirLights:L.directional.length,numPointLights:L.point.length,numSpotLights:L.spot.length,numSpotLightMaps:L.spotLightMap.length,numRectAreaLights:L.rectArea.length,numHemiLights:L.hemi.length,numDirLightShadows:L.directionalShadowMap.length,numPointLightShadows:L.pointShadowMap.length,numSpotLightShadows:L.spotShadowMap.length,numSpotLightShadowsWithMaps:L.numSpotLightShadowsWithMaps,numLightProbes:L.numLightProbes,numLightProbeGrids:pe.length,numClippingPlanes:c.numPlanes,numClipIntersection:c.numIntersection,dithering:A.dithering,shadowMapEnabled:a.shadowMap.enabled&&j.length>0,shadowMapType:a.shadowMap.type,toneMapping:q,decodeVideoTexture:zt&&A.map.isVideoTexture===!0&&kt.getTransfer(A.map.colorSpace)===an,decodeVideoTextureEmissive:st&&A.emissiveMap.isVideoTexture===!0&&kt.getTransfer(A.emissiveMap.colorSpace)===an,premultipliedAlpha:A.premultipliedAlpha,doubleSided:A.side===Pa,flipSided:A.side===ui,useDepthPacking:A.depthPacking>=0,depthPacking:A.depthPacking||0,index0AttributeName:A.index0AttributeName,extensionClipCullDistance:ke&&A.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ke&&A.extensions.multiDraw===!0||Ke)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:A.customProgramCacheKey()};return Me.vertexUv1s=m.has(1),Me.vertexUv2s=m.has(2),Me.vertexUv3s=m.has(3),m.clear(),Me}function v(A){const L=[];if(A.shaderID?L.push(A.shaderID):(L.push(A.customVertexShaderID),L.push(A.customFragmentShaderID)),A.defines!==void 0)for(const j in A.defines)L.push(j),L.push(A.defines[j]);return A.isRawShaderMaterial===!1&&(x(L,A),B(L,A),L.push(a.outputColorSpace)),L.push(A.customProgramCacheKey),L.join()}function x(A,L){A.push(L.precision),A.push(L.outputColorSpace),A.push(L.envMapMode),A.push(L.envMapCubeUVHeight),A.push(L.mapUv),A.push(L.alphaMapUv),A.push(L.lightMapUv),A.push(L.aoMapUv),A.push(L.bumpMapUv),A.push(L.normalMapUv),A.push(L.displacementMapUv),A.push(L.emissiveMapUv),A.push(L.metalnessMapUv),A.push(L.roughnessMapUv),A.push(L.anisotropyMapUv),A.push(L.clearcoatMapUv),A.push(L.clearcoatNormalMapUv),A.push(L.clearcoatRoughnessMapUv),A.push(L.iridescenceMapUv),A.push(L.iridescenceThicknessMapUv),A.push(L.sheenColorMapUv),A.push(L.sheenRoughnessMapUv),A.push(L.specularMapUv),A.push(L.specularColorMapUv),A.push(L.specularIntensityMapUv),A.push(L.transmissionMapUv),A.push(L.thicknessMapUv),A.push(L.combine),A.push(L.fogExp2),A.push(L.sizeAttenuation),A.push(L.morphTargetsCount),A.push(L.morphAttributeCount),A.push(L.numDirLights),A.push(L.numPointLights),A.push(L.numSpotLights),A.push(L.numSpotLightMaps),A.push(L.numHemiLights),A.push(L.numRectAreaLights),A.push(L.numDirLightShadows),A.push(L.numPointLightShadows),A.push(L.numSpotLightShadows),A.push(L.numSpotLightShadowsWithMaps),A.push(L.numLightProbes),A.push(L.shadowMapType),A.push(L.toneMapping),A.push(L.numClippingPlanes),A.push(L.numClipIntersection),A.push(L.depthPacking)}function B(A,L){f.disableAll(),L.instancing&&f.enable(0),L.instancingColor&&f.enable(1),L.instancingMorph&&f.enable(2),L.matcap&&f.enable(3),L.envMap&&f.enable(4),L.normalMapObjectSpace&&f.enable(5),L.normalMapTangentSpace&&f.enable(6),L.clearcoat&&f.enable(7),L.iridescence&&f.enable(8),L.alphaTest&&f.enable(9),L.vertexColors&&f.enable(10),L.vertexAlphas&&f.enable(11),L.vertexUv1s&&f.enable(12),L.vertexUv2s&&f.enable(13),L.vertexUv3s&&f.enable(14),L.vertexTangents&&f.enable(15),L.anisotropy&&f.enable(16),L.alphaHash&&f.enable(17),L.batching&&f.enable(18),L.dispersion&&f.enable(19),L.batchingColor&&f.enable(20),L.gradientMap&&f.enable(21),L.packedNormalMap&&f.enable(22),L.vertexNormals&&f.enable(23),A.push(f.mask),f.disableAll(),L.fog&&f.enable(0),L.useFog&&f.enable(1),L.flatShading&&f.enable(2),L.logarithmicDepthBuffer&&f.enable(3),L.reversedDepthBuffer&&f.enable(4),L.skinning&&f.enable(5),L.morphTargets&&f.enable(6),L.morphNormals&&f.enable(7),L.morphColors&&f.enable(8),L.premultipliedAlpha&&f.enable(9),L.shadowMapEnabled&&f.enable(10),L.doubleSided&&f.enable(11),L.flipSided&&f.enable(12),L.useDepthPacking&&f.enable(13),L.dithering&&f.enable(14),L.transmission&&f.enable(15),L.sheen&&f.enable(16),L.opaque&&f.enable(17),L.pointsUvs&&f.enable(18),L.decodeVideoTexture&&f.enable(19),L.decodeVideoTextureEmissive&&f.enable(20),L.alphaToCoverage&&f.enable(21),L.numLightProbeGrids>0&&f.enable(22),L.hasPositionAttribute&&f.enable(23),A.push(f.mask)}function P(A){const L=b[A.type];let j;if(L){const V=aa[L];j=_E.clone(V.uniforms)}else j=A.uniforms;return j}function D(A,L){let j=y.get(L);return j!==void 0?++j.usedTimes:(j=new ZC(a,L,A,l),h.push(j),y.set(L,j)),j}function O(A){if(--A.usedTimes===0){const L=h.indexOf(A);h[L]=h[h.length-1],h.pop(),y.delete(A.cacheKey),A.destroy()}}function U(A){p.remove(A)}function N(){p.dispose()}return{getParameters:C,getProgramCacheKey:v,getUniforms:P,acquireProgram:D,releaseProgram:O,releaseShaderCache:U,programs:h,dispose:N}}function tw(){let a=new WeakMap;function e(f){return a.has(f)}function i(f){let p=a.get(f);return p===void 0&&(p={},a.set(f,p)),p}function s(f){a.delete(f)}function l(f,p,m){a.get(f)[p]=m}function c(){a=new WeakMap}return{has:e,get:i,remove:s,update:l,dispose:c}}function nw(a,e){return a.groupOrder!==e.groupOrder?a.groupOrder-e.groupOrder:a.renderOrder!==e.renderOrder?a.renderOrder-e.renderOrder:a.material.id!==e.material.id?a.material.id-e.material.id:a.materialVariant!==e.materialVariant?a.materialVariant-e.materialVariant:a.z!==e.z?a.z-e.z:a.id-e.id}function Jv(a,e){return a.groupOrder!==e.groupOrder?a.groupOrder-e.groupOrder:a.renderOrder!==e.renderOrder?a.renderOrder-e.renderOrder:a.z!==e.z?e.z-a.z:a.id-e.id}function ex(){const a=[];let e=0;const i=[],s=[],l=[];function c(){e=0,i.length=0,s.length=0,l.length=0}function f(_){let b=0;return _.isInstancedMesh&&(b+=2),_.isSkinnedMesh&&(b+=1),b}function p(_,b,T,C,v,x){let B=a[e];return B===void 0?(B={id:_.id,object:_,geometry:b,material:T,materialVariant:f(_),groupOrder:C,renderOrder:_.renderOrder,z:v,group:x},a[e]=B):(B.id=_.id,B.object=_,B.geometry=b,B.material=T,B.materialVariant=f(_),B.groupOrder=C,B.renderOrder=_.renderOrder,B.z=v,B.group=x),e++,B}function m(_,b,T,C,v,x){const B=p(_,b,T,C,v,x);T.transmission>0?s.push(B):T.transparent===!0?l.push(B):i.push(B)}function h(_,b,T,C,v,x){const B=p(_,b,T,C,v,x);T.transmission>0?s.unshift(B):T.transparent===!0?l.unshift(B):i.unshift(B)}function y(_,b,T){i.length>1&&i.sort(_||nw),s.length>1&&s.sort(b||Jv),l.length>1&&l.sort(b||Jv),T&&(i.reverse(),s.reverse(),l.reverse())}function S(){for(let _=e,b=a.length;_=c.length?(f=new ex,c.push(f)):f=c[l],f}function i(){a=new WeakMap}return{get:e,dispose:i}}function aw(){const a={};return{get:function(e){if(a[e.id]!==void 0)return a[e.id];let i;switch(e.type){case"DirectionalLight":i={direction:new ie,color:new dt};break;case"SpotLight":i={position:new ie,direction:new ie,color:new dt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new ie,color:new dt,distance:0,decay:0};break;case"HemisphereLight":i={direction:new ie,skyColor:new dt,groundColor:new dt};break;case"RectAreaLight":i={color:new dt,position:new ie,halfWidth:new ie,halfHeight:new ie};break}return a[e.id]=i,i}}}function sw(){const a={};return{get:function(e){if(a[e.id]!==void 0)return a[e.id];let i;switch(e.type){case"DirectionalLight":i={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bt};break;case"SpotLight":i={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bt};break;case"PointLight":i={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bt,shadowCameraNear:1,shadowCameraFar:1e3};break}return a[e.id]=i,i}}}let rw=0;function ow(a,e){return(e.castShadow?2:0)-(a.castShadow?2:0)+(e.map?1:0)-(a.map?1:0)}function lw(a){const e=new aw,i=sw(),s={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let h=0;h<9;h++)s.probe.push(new ie);const l=new ie,c=new dn,f=new dn;function p(h){let y=0,S=0,_=0;for(let L=0;L<9;L++)s.probe[L].set(0,0,0);let b=0,T=0,C=0,v=0,x=0,B=0,P=0,D=0,O=0,U=0,N=0;h.sort(ow);for(let L=0,j=h.length;L0&&(a.has("OES_texture_float_linear")===!0?(s.rectAreaLTC1=We.LTC_FLOAT_1,s.rectAreaLTC2=We.LTC_FLOAT_2):(s.rectAreaLTC1=We.LTC_HALF_1,s.rectAreaLTC2=We.LTC_HALF_2)),s.ambient[0]=y,s.ambient[1]=S,s.ambient[2]=_;const A=s.hash;(A.directionalLength!==b||A.pointLength!==T||A.spotLength!==C||A.rectAreaLength!==v||A.hemiLength!==x||A.numDirectionalShadows!==B||A.numPointShadows!==P||A.numSpotShadows!==D||A.numSpotMaps!==O||A.numLightProbes!==N)&&(s.directional.length=b,s.spot.length=C,s.rectArea.length=v,s.point.length=T,s.hemi.length=x,s.directionalShadow.length=B,s.directionalShadowMap.length=B,s.pointShadow.length=P,s.pointShadowMap.length=P,s.spotShadow.length=D,s.spotShadowMap.length=D,s.directionalShadowMatrix.length=B,s.pointShadowMatrix.length=P,s.spotLightMatrix.length=D+O-U,s.spotLightMap.length=O,s.numSpotLightShadowsWithMaps=U,s.numLightProbes=N,A.directionalLength=b,A.pointLength=T,A.spotLength=C,A.rectAreaLength=v,A.hemiLength=x,A.numDirectionalShadows=B,A.numPointShadows=P,A.numSpotShadows=D,A.numSpotMaps=O,A.numLightProbes=N,s.version=rw++)}function m(h,y){let S=0,_=0,b=0,T=0,C=0;const v=y.matrixWorldInverse;for(let x=0,B=h.length;x=f.length?(p=new tx(a),f.push(p)):p=f[c],p}function s(){e=new WeakMap}return{get:i,dispose:s}}const uw=`void main() { gl_Position = vec4( position, 1.0 ); }`,fw=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); }`,dw=[new ie(1,0,0),new ie(-1,0,0),new ie(0,1,0),new ie(0,-1,0),new ie(0,0,1),new ie(0,0,-1)],hw=[new ie(0,-1,0),new ie(0,-1,0),new ie(0,0,1),new ie(0,0,-1),new ie(0,-1,0),new ie(0,-1,0)],nx=new dn,vl=new ie,Rh=new ie;function pw(a,e,i){let s=new Xp;const l=new bt,c=new bt,f=new xn,p=new ME,m=new bE,h={},y=i.maxTextureSize,S={[Ts]:ui,[ui]:Ts,[Pa]:Pa},_=new ca({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new bt},radius:{value:4}},vertexShader:uw,fragmentShader:fw}),b=_.clone();b.defines.HORIZONTAL_PASS=1;const T=new Fi;T.setAttribute("position",new Zi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const C=new Ki(T,_),v=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=_u;let x=this.type;this.render=function(U,N,A){if(v.enabled===!1||v.autoUpdate===!1&&v.needsUpdate===!1||U.length===0)return;this.type===Ax&&(_t("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=_u);const L=a.getRenderTarget(),j=a.getActiveCubeFace(),V=a.getActiveMipmapLevel(),$=a.state;$.setBlending(Ba),$.buffers.depth.getReversed()===!0?$.buffers.color.setClear(0,0,0,0):$.buffers.color.setClear(1,1,1,1),$.buffers.depth.setTest(!0),$.setScissorTest(!1);const pe=x!==this.type;pe&&N.traverse(function(ge){ge.material&&(Array.isArray(ge.material)?ge.material.forEach(K=>K.needsUpdate=!0):ge.material.needsUpdate=!0)});for(let ge=0,K=U.length;gey||l.y>y)&&(l.x>y&&(c.x=Math.floor(y/ne.x),l.x=c.x*ne.x,G.mapSize.x=c.x),l.y>y&&(c.y=Math.floor(y/ne.y),l.y=c.y*ne.y,G.mapSize.y=c.y));const ye=a.state.buffers.depth.getReversed();if(G.camera._reversedDepth=ye,G.map===null||pe===!0){if(G.map!==null&&(G.map.depthTexture!==null&&(G.map.depthTexture.dispose(),G.map.depthTexture=null),G.map.dispose()),this.type===xl){if(H.isPointLight){_t("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}G.map=new oa(l.x,l.y,{format:ir,type:Ha,minFilter:$n,magFilter:$n,generateMipmaps:!1}),G.map.texture.name=H.name+".shadowMap",G.map.depthTexture=new ho(l.x,l.y,qi),G.map.depthTexture.name=H.name+".shadowMapDepth",G.map.depthTexture.format=Ga,G.map.depthTexture.compareFunction=null,G.map.depthTexture.minFilter=Wn,G.map.depthTexture.magFilter=Wn}else H.isPointLight?(G.map=new ny(l.x),G.map.depthTexture=new pE(l.x,la)):(G.map=new oa(l.x,l.y),G.map.depthTexture=new ho(l.x,l.y,la)),G.map.depthTexture.name=H.name+".shadowMap",G.map.depthTexture.format=Ga,this.type===_u?(G.map.depthTexture.compareFunction=ye?Vp:Gp,G.map.depthTexture.minFilter=$n,G.map.depthTexture.magFilter=$n):(G.map.depthTexture.compareFunction=null,G.map.depthTexture.minFilter=Wn,G.map.depthTexture.magFilter=Wn);G.camera.updateProjectionMatrix()}const xe=G.map.isWebGLCubeRenderTarget?6:1;for(let F=0;F0||N.map&&N.alphaTest>0||N.alphaToCoverage===!0){const $=j.uuid,pe=N.uuid;let ge=h[$];ge===void 0&&(ge={},h[$]=ge);let K=ge[pe];K===void 0&&(K=j.clone(),ge[pe]=K,N.addEventListener("dispose",O)),j=K}if(j.visible=N.visible,j.wireframe=N.wireframe,L===xl?j.side=N.shadowSide!==null?N.shadowSide:N.side:j.side=N.shadowSide!==null?N.shadowSide:S[N.side],j.alphaMap=N.alphaMap,j.alphaTest=N.alphaToCoverage===!0?.5:N.alphaTest,j.map=N.map,j.clipShadows=N.clipShadows,j.clippingPlanes=N.clippingPlanes,j.clipIntersection=N.clipIntersection,j.displacementMap=N.displacementMap,j.displacementScale=N.displacementScale,j.displacementBias=N.displacementBias,j.wireframeLinewidth=N.wireframeLinewidth,j.linewidth=N.linewidth,A.isPointLight===!0&&j.isMeshDistanceMaterial===!0){const $=a.properties.get(j);$.light=A}return j}function D(U,N,A,L,j){if(U.visible===!1)return;if(U.layers.test(N.layers)&&(U.isMesh||U.isLine||U.isPoints)&&(U.castShadow||U.receiveShadow&&j===xl)&&(!U.frustumCulled||s.intersectsObject(U))){U.modelViewMatrix.multiplyMatrices(A.matrixWorldInverse,U.matrixWorld);const pe=e.update(U),ge=U.material;if(Array.isArray(ge)){const K=pe.groups;for(let H=0,G=K.length;H=1):ye.indexOf("OpenGL ES")!==-1&&(ne=parseFloat(/^OpenGL ES (\d)/.exec(ye)[1]),G=ne>=2);let xe=null,F={};const J=a.getParameter(a.SCISSOR_BOX),Ce=a.getParameter(a.VIEWPORT),Ue=new xn().fromArray(J),Ie=new xn().fromArray(Ce);function ae(Z,Pe,Se,Be){const ke=new Uint8Array(4),q=a.createTexture();a.bindTexture(Z,q),a.texParameteri(Z,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(Z,a.TEXTURE_MAG_FILTER,a.NEAREST);for(let Me=0;Me"u"?!1:/OculusBrowser/g.test(navigator.userAgent),h=new bt,y=new WeakMap,S=new Set;let _;const b=new WeakMap;let T=!1;try{T=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function C(I,E){return T?new OffscreenCanvas(I,E):wu("canvas")}function v(I,E,X){let se=1;const me=xt(I);if((me.width>X||me.height>X)&&(se=X/Math.max(me.width,me.height)),se<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const Ne=Math.floor(se*me.width),Oe=Math.floor(se*me.height);_===void 0&&(_=C(Ne,Oe));const _e=E?C(Ne,Oe):_;return _e.width=Ne,_e.height=Oe,_e.getContext("2d").drawImage(I,0,0,Ne,Oe),_t("WebGLRenderer: Texture has been resized from ("+me.width+"x"+me.height+") to ("+Ne+"x"+Oe+")."),_e}else return"data"in I&&_t("WebGLRenderer: Image in DataTexture is too big ("+me.width+"x"+me.height+")."),I;return I}function x(I){return I.generateMipmaps}function B(I){a.generateMipmap(I)}function P(I){return I.isWebGLCubeRenderTarget?a.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?a.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?a.TEXTURE_2D_ARRAY:a.TEXTURE_2D}function D(I,E,X,se,me,Ne=!1){if(I!==null){if(a[I]!==void 0)return a[I];_t("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let Oe;se&&(Oe=e.get("EXT_texture_norm16"),Oe||_t("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let _e=E;if(E===a.RED&&(X===a.FLOAT&&(_e=a.R32F),X===a.HALF_FLOAT&&(_e=a.R16F),X===a.UNSIGNED_BYTE&&(_e=a.R8),X===a.UNSIGNED_SHORT&&Oe&&(_e=Oe.R16_EXT),X===a.SHORT&&Oe&&(_e=Oe.R16_SNORM_EXT)),E===a.RED_INTEGER&&(X===a.UNSIGNED_BYTE&&(_e=a.R8UI),X===a.UNSIGNED_SHORT&&(_e=a.R16UI),X===a.UNSIGNED_INT&&(_e=a.R32UI),X===a.BYTE&&(_e=a.R8I),X===a.SHORT&&(_e=a.R16I),X===a.INT&&(_e=a.R32I)),E===a.RG&&(X===a.FLOAT&&(_e=a.RG32F),X===a.HALF_FLOAT&&(_e=a.RG16F),X===a.UNSIGNED_BYTE&&(_e=a.RG8),X===a.UNSIGNED_SHORT&&Oe&&(_e=Oe.RG16_EXT),X===a.SHORT&&Oe&&(_e=Oe.RG16_SNORM_EXT)),E===a.RG_INTEGER&&(X===a.UNSIGNED_BYTE&&(_e=a.RG8UI),X===a.UNSIGNED_SHORT&&(_e=a.RG16UI),X===a.UNSIGNED_INT&&(_e=a.RG32UI),X===a.BYTE&&(_e=a.RG8I),X===a.SHORT&&(_e=a.RG16I),X===a.INT&&(_e=a.RG32I)),E===a.RGB_INTEGER&&(X===a.UNSIGNED_BYTE&&(_e=a.RGB8UI),X===a.UNSIGNED_SHORT&&(_e=a.RGB16UI),X===a.UNSIGNED_INT&&(_e=a.RGB32UI),X===a.BYTE&&(_e=a.RGB8I),X===a.SHORT&&(_e=a.RGB16I),X===a.INT&&(_e=a.RGB32I)),E===a.RGBA_INTEGER&&(X===a.UNSIGNED_BYTE&&(_e=a.RGBA8UI),X===a.UNSIGNED_SHORT&&(_e=a.RGBA16UI),X===a.UNSIGNED_INT&&(_e=a.RGBA32UI),X===a.BYTE&&(_e=a.RGBA8I),X===a.SHORT&&(_e=a.RGBA16I),X===a.INT&&(_e=a.RGBA32I)),E===a.RGB&&(X===a.UNSIGNED_SHORT&&Oe&&(_e=Oe.RGB16_EXT),X===a.SHORT&&Oe&&(_e=Oe.RGB16_SNORM_EXT),X===a.UNSIGNED_INT_5_9_9_9_REV&&(_e=a.RGB9_E5),X===a.UNSIGNED_INT_10F_11F_11F_REV&&(_e=a.R11F_G11F_B10F)),E===a.RGBA){const he=Ne?Cu:kt.getTransfer(me);X===a.FLOAT&&(_e=a.RGBA32F),X===a.HALF_FLOAT&&(_e=a.RGBA16F),X===a.UNSIGNED_BYTE&&(_e=he===an?a.SRGB8_ALPHA8:a.RGBA8),X===a.UNSIGNED_SHORT&&Oe&&(_e=Oe.RGBA16_EXT),X===a.SHORT&&Oe&&(_e=Oe.RGBA16_SNORM_EXT),X===a.UNSIGNED_SHORT_4_4_4_4&&(_e=a.RGBA4),X===a.UNSIGNED_SHORT_5_5_5_1&&(_e=a.RGB5_A1)}return(_e===a.R16F||_e===a.R32F||_e===a.RG16F||_e===a.RG32F||_e===a.RGBA16F||_e===a.RGBA32F)&&e.get("EXT_color_buffer_float"),_e}function O(I,E){let X;return I?E===null||E===la||E===Cl?X=a.DEPTH24_STENCIL8:E===qi?X=a.DEPTH32F_STENCIL8:E===Al&&(X=a.DEPTH24_STENCIL8,_t("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):E===null||E===la||E===Cl?X=a.DEPTH_COMPONENT24:E===qi?X=a.DEPTH_COMPONENT32F:E===Al&&(X=a.DEPTH_COMPONENT16),X}function U(I,E){return x(I)===!0||I.isFramebufferTexture&&I.minFilter!==Wn&&I.minFilter!==$n?Math.log2(Math.max(E.width,E.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?E.mipmaps.length:1}function N(I){const E=I.target;E.removeEventListener("dispose",N),L(E),E.isVideoTexture&&y.delete(E),E.isHTMLTexture&&S.delete(E)}function A(I){const E=I.target;E.removeEventListener("dispose",A),V(E)}function L(I){const E=s.get(I);if(E.__webglInit===void 0)return;const X=I.source,se=b.get(X);if(se){const me=se[E.__cacheKey];me.usedTimes--,me.usedTimes===0&&j(I),Object.keys(se).length===0&&b.delete(X)}s.remove(I)}function j(I){const E=s.get(I);a.deleteTexture(E.__webglTexture);const X=I.source,se=b.get(X);delete se[E.__cacheKey],f.memory.textures--}function V(I){const E=s.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),s.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let se=0;se<6;se++){if(Array.isArray(E.__webglFramebuffer[se]))for(let me=0;me=l.maxTextures&&_t("WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+l.maxTextures),$+=1,I}function G(I){const E=[];return E.push(I.wrapS),E.push(I.wrapT),E.push(I.wrapR||0),E.push(I.magFilter),E.push(I.minFilter),E.push(I.anisotropy),E.push(I.internalFormat),E.push(I.format),E.push(I.type),E.push(I.generateMipmaps),E.push(I.premultiplyAlpha),E.push(I.flipY),E.push(I.unpackAlignment),E.push(I.colorSpace),E.join()}function ne(I,E){const X=s.get(I);if(I.isVideoTexture&&z(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&X.__version!==I.version){const se=I.image;if(se===null)_t("WebGLRenderer: Texture marked for update but no image data found.");else if(se.complete===!1)_t("WebGLRenderer: Texture marked for update but image is incomplete");else{He(X,I,E);return}}else I.isExternalTexture&&(X.__webglTexture=I.sourceTexture?I.sourceTexture:null);i.bindTexture(a.TEXTURE_2D,X.__webglTexture,a.TEXTURE0+E)}function ye(I,E){const X=s.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&X.__version!==I.version){He(X,I,E);return}else I.isExternalTexture&&(X.__webglTexture=I.sourceTexture?I.sourceTexture:null);i.bindTexture(a.TEXTURE_2D_ARRAY,X.__webglTexture,a.TEXTURE0+E)}function xe(I,E){const X=s.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&X.__version!==I.version){He(X,I,E);return}i.bindTexture(a.TEXTURE_3D,X.__webglTexture,a.TEXTURE0+E)}function F(I,E){const X=s.get(I);if(I.isCubeDepthTexture!==!0&&I.version>0&&X.__version!==I.version){nt(X,I,E);return}i.bindTexture(a.TEXTURE_CUBE_MAP,X.__webglTexture,a.TEXTURE0+E)}const J={[kh]:a.REPEAT,[Ia]:a.CLAMP_TO_EDGE,[jh]:a.MIRRORED_REPEAT},Ce={[Wn]:a.NEAREST,[Cb]:a.NEAREST_MIPMAP_NEAREST,[Gc]:a.NEAREST_MIPMAP_LINEAR,[$n]:a.LINEAR,[$d]:a.LINEAR_MIPMAP_NEAREST,[Js]:a.LINEAR_MIPMAP_LINEAR},Ue={[Db]:a.NEVER,[Pb]:a.ALWAYS,[Nb]:a.LESS,[Gp]:a.LEQUAL,[Ub]:a.EQUAL,[Vp]:a.GEQUAL,[Lb]:a.GREATER,[Ob]:a.NOTEQUAL};function Ie(I,E){if(E.type===qi&&e.has("OES_texture_float_linear")===!1&&(E.magFilter===$n||E.magFilter===$d||E.magFilter===Gc||E.magFilter===Js||E.minFilter===$n||E.minFilter===$d||E.minFilter===Gc||E.minFilter===Js)&&_t("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),a.texParameteri(I,a.TEXTURE_WRAP_S,J[E.wrapS]),a.texParameteri(I,a.TEXTURE_WRAP_T,J[E.wrapT]),(I===a.TEXTURE_3D||I===a.TEXTURE_2D_ARRAY)&&a.texParameteri(I,a.TEXTURE_WRAP_R,J[E.wrapR]),a.texParameteri(I,a.TEXTURE_MAG_FILTER,Ce[E.magFilter]),a.texParameteri(I,a.TEXTURE_MIN_FILTER,Ce[E.minFilter]),E.compareFunction&&(a.texParameteri(I,a.TEXTURE_COMPARE_MODE,a.COMPARE_REF_TO_TEXTURE),a.texParameteri(I,a.TEXTURE_COMPARE_FUNC,Ue[E.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(E.magFilter===Wn||E.minFilter!==Gc&&E.minFilter!==Js||E.type===qi&&e.has("OES_texture_float_linear")===!1)return;if(E.anisotropy>1||s.get(E).__currentAnisotropy){const X=e.get("EXT_texture_filter_anisotropic");a.texParameterf(I,X.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(E.anisotropy,l.getMaxAnisotropy())),s.get(E).__currentAnisotropy=E.anisotropy}}}function ae(I,E){let X=!1;I.__webglInit===void 0&&(I.__webglInit=!0,E.addEventListener("dispose",N));const se=E.source;let me=b.get(se);me===void 0&&(me={},b.set(se,me));const Ne=G(E);if(Ne!==I.__cacheKey){me[Ne]===void 0&&(me[Ne]={texture:a.createTexture(),usedTimes:0},f.memory.textures++,X=!0),me[Ne].usedTimes++;const Oe=me[I.__cacheKey];Oe!==void 0&&(me[I.__cacheKey].usedTimes--,Oe.usedTimes===0&&j(E)),I.__cacheKey=Ne,I.__webglTexture=me[Ne].texture}return X}function Ae(I,E,X){return Math.floor(Math.floor(I/X)/E)}function Ee(I,E,X,se){const Ne=I.updateRanges;if(Ne.length===0)i.texSubImage2D(a.TEXTURE_2D,0,0,0,E.width,E.height,X,se,E.data);else{Ne.sort((je,ze)=>je.start-ze.start);let Oe=0;for(let je=1;je0){Je&&pt&&i.texStorage2D(a.TEXTURE_2D,Pe,ze,Qe[0].width,Qe[0].height);for(let Se=0,Be=Qe.length;Se0){const ke=Lv(Fe.width,Fe.height,E.format,E.type);for(const q of E.layerUpdates){const Me=Fe.data.subarray(q*ke/Fe.data.BYTES_PER_ELEMENT,(q+1)*ke/Fe.data.BYTES_PER_ELEMENT);i.compressedTexSubImage3D(a.TEXTURE_2D_ARRAY,Se,0,0,q,Fe.width,Fe.height,1,Le,Me)}E.clearLayerUpdates()}else i.compressedTexSubImage3D(a.TEXTURE_2D_ARRAY,Se,0,0,0,Fe.width,Fe.height,he.depth,Le,Fe.data)}else i.compressedTexImage3D(a.TEXTURE_2D_ARRAY,Se,ze,Fe.width,Fe.height,he.depth,0,Fe.data,0,0);else _t("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Je?Z&&i.texSubImage3D(a.TEXTURE_2D_ARRAY,Se,0,0,0,Fe.width,Fe.height,he.depth,Le,je,Fe.data):i.texImage3D(a.TEXTURE_2D_ARRAY,Se,ze,Fe.width,Fe.height,he.depth,0,Le,je,Fe.data)}else{Je&&pt&&i.texStorage2D(a.TEXTURE_2D,Pe,ze,Qe[0].width,Qe[0].height);for(let Se=0,Be=Qe.length;Se0){const Se=Lv(he.width,he.height,E.format,E.type);for(const Be of E.layerUpdates){const ke=he.data.subarray(Be*Se/he.data.BYTES_PER_ELEMENT,(Be+1)*Se/he.data.BYTES_PER_ELEMENT);i.texSubImage3D(a.TEXTURE_2D_ARRAY,0,0,0,Be,he.width,he.height,1,Le,je,ke)}E.clearLayerUpdates()}else i.texSubImage3D(a.TEXTURE_2D_ARRAY,0,0,0,0,he.width,he.height,he.depth,Le,je,he.data)}else i.texImage3D(a.TEXTURE_2D_ARRAY,0,ze,he.width,he.height,he.depth,0,Le,je,he.data);else if(E.isData3DTexture)Je?(pt&&i.texStorage3D(a.TEXTURE_3D,Pe,ze,he.width,he.height,he.depth),Z&&i.texSubImage3D(a.TEXTURE_3D,0,0,0,0,he.width,he.height,he.depth,Le,je,he.data)):i.texImage3D(a.TEXTURE_3D,0,ze,he.width,he.height,he.depth,0,Le,je,he.data);else if(E.isFramebufferTexture){if(pt)if(Je)i.texStorage2D(a.TEXTURE_2D,Pe,ze,he.width,he.height);else{let Se=he.width,Be=he.height;for(let ke=0;ke>=1,Be>>=1}}else if(E.isHTMLTexture){if("texElementImage2D"in a){const Se=a.canvas;if(Se.hasAttribute("layoutsubtree")||Se.setAttribute("layoutsubtree","true"),he.parentNode!==Se){Se.appendChild(he),S.add(E),Se.onpaint=Be=>{const ke=Be.changedElements;for(const q of S)ke.includes(q.image)&&(q.needsUpdate=!0)},Se.requestPaint();return}if(a.texElementImage2D.length===3)a.texElementImage2D(a.TEXTURE_2D,a.RGBA8,he);else{const ke=a.RGBA,q=a.RGBA,Me=a.UNSIGNED_BYTE;a.texElementImage2D(a.TEXTURE_2D,0,ke,q,Me,he)}a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE)}}else if(Qe.length>0){if(Je&&pt){const Se=xt(Qe[0]);i.texStorage2D(a.TEXTURE_2D,Pe,ze,Se.width,Se.height)}for(let Se=0,Be=Qe.length;Se0&&Be++;const q=xt(ze[0]);i.texStorage2D(a.TEXTURE_CUBE_MAP,Be,pt,q.width,q.height)}for(let q=0;q<6;q++)if(je){Z?Se&&i.texSubImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+q,0,0,0,ze[q].width,ze[q].height,Qe,Je,ze[q].data):i.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+q,0,pt,ze[q].width,ze[q].height,0,Qe,Je,ze[q].data);for(let Me=0;Me>Ne),Fe=Math.max(1,E.height>>Ne);me===a.TEXTURE_3D||me===a.TEXTURE_2D_ARRAY?i.texImage3D(me,Ne,he,ze,Fe,E.depth,0,Oe,_e,null):i.texImage2D(me,Ne,he,ze,Fe,0,Oe,_e,null)}i.bindFramebuffer(a.FRAMEBUFFER,I),W(E)?p.framebufferTexture2DMultisampleEXT(a.FRAMEBUFFER,se,me,je.__webglTexture,0,It(E)):(me===a.TEXTURE_2D||me>=a.TEXTURE_CUBE_MAP_POSITIVE_X&&me<=a.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&a.framebufferTexture2D(a.FRAMEBUFFER,se,me,je.__webglTexture,Ne),i.bindFramebuffer(a.FRAMEBUFFER,null)}function zt(I,E,X){if(a.bindRenderbuffer(a.RENDERBUFFER,I),E.depthBuffer){const se=E.depthTexture,me=se&&se.isDepthTexture?se.type:null,Ne=O(E.stencilBuffer,me),Oe=E.stencilBuffer?a.DEPTH_STENCIL_ATTACHMENT:a.DEPTH_ATTACHMENT;W(E)?p.renderbufferStorageMultisampleEXT(a.RENDERBUFFER,It(E),Ne,E.width,E.height):X?a.renderbufferStorageMultisample(a.RENDERBUFFER,It(E),Ne,E.width,E.height):a.renderbufferStorage(a.RENDERBUFFER,Ne,E.width,E.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,Oe,a.RENDERBUFFER,I)}else{const se=E.textures;for(let me=0;me{delete E.__boundDepthTexture,delete E.__depthDisposeCallback,se.removeEventListener("dispose",me)};se.addEventListener("dispose",me),E.__depthDisposeCallback=me}E.__boundDepthTexture=se}if(I.depthTexture&&!E.__autoAllocateDepthBuffer)if(X)for(let se=0;se<6;se++)ht(E.__webglFramebuffer[se],I,se);else{const se=I.texture.mipmaps;se&&se.length>0?ht(E.__webglFramebuffer[0],I,0):ht(E.__webglFramebuffer,I,0)}else if(X){E.__webglDepthbuffer=[];for(let se=0;se<6;se++)if(i.bindFramebuffer(a.FRAMEBUFFER,E.__webglFramebuffer[se]),E.__webglDepthbuffer[se]===void 0)E.__webglDepthbuffer[se]=a.createRenderbuffer(),zt(E.__webglDepthbuffer[se],I,!1);else{const me=I.stencilBuffer?a.DEPTH_STENCIL_ATTACHMENT:a.DEPTH_ATTACHMENT,Ne=E.__webglDepthbuffer[se];a.bindRenderbuffer(a.RENDERBUFFER,Ne),a.framebufferRenderbuffer(a.FRAMEBUFFER,me,a.RENDERBUFFER,Ne)}}else{const se=I.texture.mipmaps;if(se&&se.length>0?i.bindFramebuffer(a.FRAMEBUFFER,E.__webglFramebuffer[0]):i.bindFramebuffer(a.FRAMEBUFFER,E.__webglFramebuffer),E.__webglDepthbuffer===void 0)E.__webglDepthbuffer=a.createRenderbuffer(),zt(E.__webglDepthbuffer,I,!1);else{const me=I.stencilBuffer?a.DEPTH_STENCIL_ATTACHMENT:a.DEPTH_ATTACHMENT,Ne=E.__webglDepthbuffer;a.bindRenderbuffer(a.RENDERBUFFER,Ne),a.framebufferRenderbuffer(a.FRAMEBUFFER,me,a.RENDERBUFFER,Ne)}}i.bindFramebuffer(a.FRAMEBUFFER,null)}function yt(I,E,X){const se=s.get(I);E!==void 0&&Ke(se.__webglFramebuffer,I,I.texture,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,0),X!==void 0&&Et(I)}function St(I){const E=I.texture,X=s.get(I),se=s.get(E);I.addEventListener("dispose",A);const me=I.textures,Ne=I.isWebGLCubeRenderTarget===!0,Oe=me.length>1;if(Oe||(se.__webglTexture===void 0&&(se.__webglTexture=a.createTexture()),se.__version=E.version,f.memory.textures++),Ne){X.__webglFramebuffer=[];for(let _e=0;_e<6;_e++)if(E.mipmaps&&E.mipmaps.length>0){X.__webglFramebuffer[_e]=[];for(let he=0;he0){X.__webglFramebuffer=[];for(let _e=0;_e0&&W(I)===!1){X.__webglMultisampledFramebuffer=a.createFramebuffer(),X.__webglColorRenderbuffer=[],i.bindFramebuffer(a.FRAMEBUFFER,X.__webglMultisampledFramebuffer);for(let _e=0;_e0)for(let he=0;he0)for(let he=0;he0){if(W(I)===!1){const E=I.textures,X=I.width,se=I.height;let me=a.COLOR_BUFFER_BIT;const Ne=I.stencilBuffer?a.DEPTH_STENCIL_ATTACHMENT:a.DEPTH_ATTACHMENT,Oe=s.get(I),_e=E.length>1;if(_e)for(let Le=0;Le0?i.bindFramebuffer(a.DRAW_FRAMEBUFFER,Oe.__webglFramebuffer[0]):i.bindFramebuffer(a.DRAW_FRAMEBUFFER,Oe.__webglFramebuffer);for(let Le=0;Le0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&E.__useRenderToTexture!==!1}function z(I){const E=f.render.frame;y.get(I)!==E&&(y.set(I,E),I.update())}function Ye(I,E){const X=I.colorSpace,se=I.format,me=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||X!==Au&&X!==Ms&&(kt.getTransfer(X)===an?(se!==Yi||me!==Ei)&&_t("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):jt("WebGLTextures: Unsupported texture color space:",X)),E}function xt(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(h.width=I.naturalWidth||I.width,h.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(h.width=I.displayWidth,h.height=I.displayHeight):(h.width=I.width,h.height=I.height),h}this.allocateTextureUnit=H,this.resetTextureUnits=pe,this.getTextureUnits=ge,this.setTextureUnits=K,this.setTexture2D=ne,this.setTexture2DArray=ye,this.setTexture3D=xe,this.setTextureCube=F,this.rebindTextures=yt,this.setupRenderTarget=St,this.updateRenderTargetMipmap=Mt,this.updateMultisampleRenderTarget=st,this.setupDepthRenderbuffer=Et,this.setupFrameBufferTexture=Ke,this.useMultisampledRTT=W,this.isReversedDepthBuffer=function(){return i.buffers.depth.getReversed()}}function _w(a,e){function i(s,l=Ms){let c;const f=kt.getTransfer(l);if(s===Ei)return a.UNSIGNED_BYTE;if(s===Pp)return a.UNSIGNED_SHORT_4_4_4_4;if(s===Ip)return a.UNSIGNED_SHORT_5_5_5_1;if(s===Bx)return a.UNSIGNED_INT_5_9_9_9_REV;if(s===Fx)return a.UNSIGNED_INT_10F_11F_11F_REV;if(s===Px)return a.BYTE;if(s===Ix)return a.SHORT;if(s===Al)return a.UNSIGNED_SHORT;if(s===Op)return a.INT;if(s===la)return a.UNSIGNED_INT;if(s===qi)return a.FLOAT;if(s===Ha)return a.HALF_FLOAT;if(s===zx)return a.ALPHA;if(s===Hx)return a.RGB;if(s===Yi)return a.RGBA;if(s===Ga)return a.DEPTH_COMPONENT;if(s===er)return a.DEPTH_STENCIL;if(s===Bp)return a.RED;if(s===Fp)return a.RED_INTEGER;if(s===ir)return a.RG;if(s===zp)return a.RG_INTEGER;if(s===Hp)return a.RGBA_INTEGER;if(s===vu||s===xu||s===yu||s===Su)if(f===an)if(c=e.get("WEBGL_compressed_texture_s3tc_srgb"),c!==null){if(s===vu)return c.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===xu)return c.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===yu)return c.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===Su)return c.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(c=e.get("WEBGL_compressed_texture_s3tc"),c!==null){if(s===vu)return c.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===xu)return c.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===yu)return c.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===Su)return c.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===Xh||s===Wh||s===qh||s===Yh)if(c=e.get("WEBGL_compressed_texture_pvrtc"),c!==null){if(s===Xh)return c.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===Wh)return c.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===qh)return c.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===Yh)return c.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===Zh||s===Kh||s===$h||s===Qh||s===Jh||s===Eu||s===ep)if(c=e.get("WEBGL_compressed_texture_etc"),c!==null){if(s===Zh||s===Kh)return f===an?c.COMPRESSED_SRGB8_ETC2:c.COMPRESSED_RGB8_ETC2;if(s===$h)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:c.COMPRESSED_RGBA8_ETC2_EAC;if(s===Qh)return c.COMPRESSED_R11_EAC;if(s===Jh)return c.COMPRESSED_SIGNED_R11_EAC;if(s===Eu)return c.COMPRESSED_RG11_EAC;if(s===ep)return c.COMPRESSED_SIGNED_RG11_EAC}else return null;if(s===tp||s===np||s===ip||s===ap||s===sp||s===rp||s===op||s===lp||s===cp||s===up||s===fp||s===dp||s===hp||s===pp)if(c=e.get("WEBGL_compressed_texture_astc"),c!==null){if(s===tp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:c.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===np)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:c.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===ip)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:c.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===ap)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:c.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===sp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:c.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===rp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:c.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===op)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:c.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===lp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:c.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===cp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:c.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===up)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:c.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===fp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:c.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===dp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:c.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===hp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:c.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===pp)return f===an?c.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:c.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===mp||s===gp||s===_p)if(c=e.get("EXT_texture_compression_bptc"),c!==null){if(s===mp)return f===an?c.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:c.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===gp)return c.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===_p)return c.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===vp||s===xp||s===Tu||s===yp)if(c=e.get("EXT_texture_compression_rgtc"),c!==null){if(s===vp)return c.COMPRESSED_RED_RGTC1_EXT;if(s===xp)return c.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===Tu)return c.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===yp)return c.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===Cl?a.UNSIGNED_INT_24_8:a[s]!==void 0?a[s]:null}return{convert:i}}const vw=` void main() { gl_Position = vec4( position, 1.0 ); }`,xw=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; void main() { vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); if ( coord.x >= 1.0 ) { gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; } else { gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; } }`;class yw{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,i){if(this.texture===null){const s=new $x(e.texture);(e.depthNear!==i.depthNear||e.depthFar!==i.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=s}}getMesh(e){if(this.texture!==null&&this.mesh===null){const i=e.cameras[0].viewport,s=new ca({vertexShader:vw,fragmentShader:xw,uniforms:{depthColor:{value:this.texture},depthWidth:{value:i.z},depthHeight:{value:i.w}}});this.mesh=new Ki(new Ou(20,20),s)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Sw extends Rs{constructor(e,i){super();const s=this;let l=null,c=1,f=null,p="local-floor",m=1,h=null,y=null,S=null,_=null,b=null,T=null;const C=typeof XRWebGLBinding<"u",v=new yw,x={},B=i.getContextAttributes();let P=null,D=null;const O=[],U=[],N=new bt;let A=null;const L=new Ii;L.viewport=new xn;const j=new Ii;j.viewport=new xn;const V=[L,j],$=new RE;let pe=null,ge=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ae){let Ae=O[ae];return Ae===void 0&&(Ae=new ah,O[ae]=Ae),Ae.getTargetRaySpace()},this.getControllerGrip=function(ae){let Ae=O[ae];return Ae===void 0&&(Ae=new ah,O[ae]=Ae),Ae.getGripSpace()},this.getHand=function(ae){let Ae=O[ae];return Ae===void 0&&(Ae=new ah,O[ae]=Ae),Ae.getHandSpace()};function K(ae){const Ae=U.indexOf(ae.inputSource);if(Ae===-1)return;const Ee=O[Ae];Ee!==void 0&&(Ee.update(ae.inputSource,ae.frame,h||f),Ee.dispatchEvent({type:ae.type,data:ae.inputSource}))}function H(){l.removeEventListener("select",K),l.removeEventListener("selectstart",K),l.removeEventListener("selectend",K),l.removeEventListener("squeeze",K),l.removeEventListener("squeezestart",K),l.removeEventListener("squeezeend",K),l.removeEventListener("end",H),l.removeEventListener("inputsourceschange",G);for(let ae=0;ae=0&&(U[He]=null,O[He].disconnect(Ee))}for(let Ae=0;Ae=U.length){U.push(Ee),He=Ke;break}else if(U[Ke]===null){U[Ke]=Ee,He=Ke;break}if(He===-1)break}const nt=O[He];nt&&nt.connect(Ee)}}const ne=new ie,ye=new ie;function xe(ae,Ae,Ee){ne.setFromMatrixPosition(Ae.matrixWorld),ye.setFromMatrixPosition(Ee.matrixWorld);const He=ne.distanceTo(ye),nt=Ae.projectionMatrix.elements,Ke=Ee.projectionMatrix.elements,zt=nt[14]/(nt[10]-1),ht=nt[14]/(nt[10]+1),Et=(nt[9]+1)/nt[5],yt=(nt[9]-1)/nt[5],St=(nt[8]-1)/nt[0],Mt=(Ke[8]+1)/Ke[0],Ht=zt*St,Gt=zt*Mt,st=He/(-St+Mt),It=st*-St;if(Ae.matrixWorld.decompose(ae.position,ae.quaternion,ae.scale),ae.translateX(It),ae.translateZ(st),ae.matrixWorld.compose(ae.position,ae.quaternion,ae.scale),ae.matrixWorldInverse.copy(ae.matrixWorld).invert(),nt[10]===-1)ae.projectionMatrix.copy(Ae.projectionMatrix),ae.projectionMatrixInverse.copy(Ae.projectionMatrixInverse);else{const W=zt+st,z=ht+st,Ye=Ht-It,xt=Gt+(He-It),I=Et*ht/z*W,E=yt*ht/z*W;ae.projectionMatrix.makePerspective(Ye,xt,I,E,W,z),ae.projectionMatrixInverse.copy(ae.projectionMatrix).invert()}}function F(ae,Ae){Ae===null?ae.matrixWorld.copy(ae.matrix):ae.matrixWorld.multiplyMatrices(Ae.matrixWorld,ae.matrix),ae.matrixWorldInverse.copy(ae.matrixWorld).invert()}this.updateCamera=function(ae){if(l===null)return;let Ae=ae.near,Ee=ae.far;v.texture!==null&&(v.depthNear>0&&(Ae=v.depthNear),v.depthFar>0&&(Ee=v.depthFar)),$.near=j.near=L.near=Ae,$.far=j.far=L.far=Ee,(pe!==$.near||ge!==$.far)&&(l.updateRenderState({depthNear:$.near,depthFar:$.far}),pe=$.near,ge=$.far),$.layers.mask=ae.layers.mask|6,L.layers.mask=$.layers.mask&-5,j.layers.mask=$.layers.mask&-3;const He=ae.parent,nt=$.cameras;F($,He);for(let Ke=0;Ke0&&(v.alphaTest.value=x.alphaTest);const B=e.get(x),P=B.envMap,D=B.envMapRotation;P&&(v.envMap.value=P,v.envMapRotation.value.setFromMatrix4(Mw.makeRotationFromEuler(D)).transpose(),P.isCubeTexture&&P.isRenderTargetTexture===!1&&v.envMapRotation.value.premultiply(oy),v.reflectivity.value=x.reflectivity,v.ior.value=x.ior,v.refractionRatio.value=x.refractionRatio),x.lightMap&&(v.lightMap.value=x.lightMap,v.lightMapIntensity.value=x.lightMapIntensity,i(x.lightMap,v.lightMapTransform)),x.aoMap&&(v.aoMap.value=x.aoMap,v.aoMapIntensity.value=x.aoMapIntensity,i(x.aoMap,v.aoMapTransform))}function f(v,x){v.diffuse.value.copy(x.color),v.opacity.value=x.opacity,x.map&&(v.map.value=x.map,i(x.map,v.mapTransform))}function p(v,x){v.dashSize.value=x.dashSize,v.totalSize.value=x.dashSize+x.gapSize,v.scale.value=x.scale}function m(v,x,B,P){v.diffuse.value.copy(x.color),v.opacity.value=x.opacity,v.size.value=x.size*B,v.scale.value=P*.5,x.map&&(v.map.value=x.map,i(x.map,v.uvTransform)),x.alphaMap&&(v.alphaMap.value=x.alphaMap,i(x.alphaMap,v.alphaMapTransform)),x.alphaTest>0&&(v.alphaTest.value=x.alphaTest)}function h(v,x){v.diffuse.value.copy(x.color),v.opacity.value=x.opacity,v.rotation.value=x.rotation,x.map&&(v.map.value=x.map,i(x.map,v.mapTransform)),x.alphaMap&&(v.alphaMap.value=x.alphaMap,i(x.alphaMap,v.alphaMapTransform)),x.alphaTest>0&&(v.alphaTest.value=x.alphaTest)}function y(v,x){v.specular.value.copy(x.specular),v.shininess.value=Math.max(x.shininess,1e-4)}function S(v,x){x.gradientMap&&(v.gradientMap.value=x.gradientMap)}function _(v,x){v.metalness.value=x.metalness,x.metalnessMap&&(v.metalnessMap.value=x.metalnessMap,i(x.metalnessMap,v.metalnessMapTransform)),v.roughness.value=x.roughness,x.roughnessMap&&(v.roughnessMap.value=x.roughnessMap,i(x.roughnessMap,v.roughnessMapTransform)),x.envMap&&(v.envMapIntensity.value=x.envMapIntensity)}function b(v,x,B){v.ior.value=x.ior,x.sheen>0&&(v.sheenColor.value.copy(x.sheenColor).multiplyScalar(x.sheen),v.sheenRoughness.value=x.sheenRoughness,x.sheenColorMap&&(v.sheenColorMap.value=x.sheenColorMap,i(x.sheenColorMap,v.sheenColorMapTransform)),x.sheenRoughnessMap&&(v.sheenRoughnessMap.value=x.sheenRoughnessMap,i(x.sheenRoughnessMap,v.sheenRoughnessMapTransform))),x.clearcoat>0&&(v.clearcoat.value=x.clearcoat,v.clearcoatRoughness.value=x.clearcoatRoughness,x.clearcoatMap&&(v.clearcoatMap.value=x.clearcoatMap,i(x.clearcoatMap,v.clearcoatMapTransform)),x.clearcoatRoughnessMap&&(v.clearcoatRoughnessMap.value=x.clearcoatRoughnessMap,i(x.clearcoatRoughnessMap,v.clearcoatRoughnessMapTransform)),x.clearcoatNormalMap&&(v.clearcoatNormalMap.value=x.clearcoatNormalMap,i(x.clearcoatNormalMap,v.clearcoatNormalMapTransform),v.clearcoatNormalScale.value.copy(x.clearcoatNormalScale),x.side===ui&&v.clearcoatNormalScale.value.negate())),x.dispersion>0&&(v.dispersion.value=x.dispersion),x.iridescence>0&&(v.iridescence.value=x.iridescence,v.iridescenceIOR.value=x.iridescenceIOR,v.iridescenceThicknessMinimum.value=x.iridescenceThicknessRange[0],v.iridescenceThicknessMaximum.value=x.iridescenceThicknessRange[1],x.iridescenceMap&&(v.iridescenceMap.value=x.iridescenceMap,i(x.iridescenceMap,v.iridescenceMapTransform)),x.iridescenceThicknessMap&&(v.iridescenceThicknessMap.value=x.iridescenceThicknessMap,i(x.iridescenceThicknessMap,v.iridescenceThicknessMapTransform))),x.transmission>0&&(v.transmission.value=x.transmission,v.transmissionSamplerMap.value=B.texture,v.transmissionSamplerSize.value.set(B.width,B.height),x.transmissionMap&&(v.transmissionMap.value=x.transmissionMap,i(x.transmissionMap,v.transmissionMapTransform)),v.thickness.value=x.thickness,x.thicknessMap&&(v.thicknessMap.value=x.thicknessMap,i(x.thicknessMap,v.thicknessMapTransform)),v.attenuationDistance.value=x.attenuationDistance,v.attenuationColor.value.copy(x.attenuationColor)),x.anisotropy>0&&(v.anisotropyVector.value.set(x.anisotropy*Math.cos(x.anisotropyRotation),x.anisotropy*Math.sin(x.anisotropyRotation)),x.anisotropyMap&&(v.anisotropyMap.value=x.anisotropyMap,i(x.anisotropyMap,v.anisotropyMapTransform))),v.specularIntensity.value=x.specularIntensity,v.specularColor.value.copy(x.specularColor),x.specularColorMap&&(v.specularColorMap.value=x.specularColorMap,i(x.specularColorMap,v.specularColorMapTransform)),x.specularIntensityMap&&(v.specularIntensityMap.value=x.specularIntensityMap,i(x.specularIntensityMap,v.specularIntensityMapTransform))}function T(v,x){x.matcap&&(v.matcap.value=x.matcap)}function C(v,x){const B=e.get(x).light;v.referencePosition.value.setFromMatrixPosition(B.matrixWorld),v.nearDistance.value=B.shadow.camera.near,v.farDistance.value=B.shadow.camera.far}return{refreshFogUniforms:s,refreshMaterialUniforms:l}}function Ew(a,e,i,s){let l={},c={},f=[];const p=a.getParameter(a.MAX_UNIFORM_BUFFER_BINDINGS);function m(D,O){const U=O.program;s.uniformBlockBinding(D,U)}function h(D,O){let U=l[D.id];U===void 0&&(v(D),U=y(D),l[D.id]=U,D.addEventListener("dispose",B));const N=O.program;s.updateUBOMapping(D,N);const A=e.render.frame;c[D.id]!==A&&(_(D),c[D.id]=A)}function y(D){const O=S();D.__bindingPointIndex=O;const U=a.createBuffer(),N=D.__size,A=D.usage;return a.bindBuffer(a.UNIFORM_BUFFER,U),a.bufferData(a.UNIFORM_BUFFER,N,A),a.bindBuffer(a.UNIFORM_BUFFER,null),a.bindBufferBase(a.UNIFORM_BUFFER,O,U),U}function S(){for(let D=0;D0&&(U+=N-A),D.__size=U,D.__cache={},this}function x(D){const O={boundary:0,storage:0};return typeof D=="number"||typeof D=="boolean"?(O.boundary=4,O.storage=4):D.isVector2?(O.boundary=8,O.storage=8):D.isVector3||D.isColor?(O.boundary=16,O.storage=12):D.isVector4?(O.boundary=16,O.storage=16):D.isMatrix3?(O.boundary=48,O.storage=48):D.isMatrix4?(O.boundary=64,O.storage=64):D.isTexture?_t("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(D)?(O.boundary=16,O.storage=D.byteLength):_t("WebGLRenderer: Unsupported uniform value type.",D),O}function B(D){const O=D.target;O.removeEventListener("dispose",B);const U=f.indexOf(O.__bindingPointIndex);f.splice(U,1),a.deleteBuffer(l[O.id]),delete l[O.id],delete c[O.id]}function P(){for(const D in l)a.deleteBuffer(l[D]);f=[],l={},c={}}return{bind:m,update:h,dispose:P}}const Tw=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ia=null;function Aw(){return ia===null&&(ia=new Yx(Tw,16,16,ir,Ha),ia.name="DFG_LUT",ia.minFilter=$n,ia.magFilter=$n,ia.wrapS=Ia,ia.wrapT=Ia,ia.generateMipmaps=!1,ia.needsUpdate=!0),ia}class Cw{constructor(e={}){const{canvas:i=Fb(),context:s=null,depth:l=!0,stencil:c=!1,alpha:f=!1,antialias:p=!1,premultipliedAlpha:m=!0,preserveDrawingBuffer:h=!1,powerPreference:y="default",failIfMajorPerformanceCaveat:S=!1,reversedDepthBuffer:_=!1,outputBufferType:b=Ei}=e;this.isWebGLRenderer=!0;let T;if(s!==null){if(typeof WebGLRenderingContext<"u"&&s instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");T=s.getContextAttributes().alpha}else T=f;const C=b,v=new Set([Hp,zp,Fp]),x=new Set([Ei,la,Al,Cl,Pp,Ip]),B=new Uint32Array(4),P=new Int32Array(4),D=new ie;let O=null,U=null;const N=[],A=[];let L=null;this.domElement=i,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ra,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const j=this;let V=!1,$=null,pe=null,ge=null,K=null;this._outputColorSpace=bi;let H=0,G=0,ne=null,ye=-1,xe=null;const F=new xn,J=new xn;let Ce=null;const Ue=new dt(0);let Ie=0,ae=i.width,Ae=i.height,Ee=1,He=null,nt=null;const Ke=new xn(0,0,ae,Ae),zt=new xn(0,0,ae,Ae);let ht=!1;const Et=new Xp;let yt=!1,St=!1;const Mt=new dn,Ht=new ie,Gt=new xn,st={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let It=!1;function W(){return ne===null?Ee:1}let z=s;function Ye(w,Q){return i.getContext(w,Q)}try{const w={alpha:!0,depth:l,stencil:c,antialias:p,premultipliedAlpha:m,preserveDrawingBuffer:h,powerPreference:y,failIfMajorPerformanceCaveat:S};if("setAttribute"in i&&i.setAttribute("data-engine",`three.js r${Up}`),i.addEventListener("webglcontextlost",ft,!1),i.addEventListener("webglcontextrestored",rt,!1),i.addEventListener("webglcontextcreationerror",Nt,!1),z===null){const Q="webgl2";if(z=Ye(Q,w),z===null)throw Ye(Q)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(w){throw jt("WebGLRenderer: "+w.message),w}let xt,I,E,X,se,me,Ne,Oe,_e,he,Le,je,ze,Fe,Qe,Je,pt,Z,Pe,Se,Be,ke,q;function Me(){xt=new A1(z),xt.init(),Be=new _w(z,xt),I=new v1(z,xt,e,Be),E=new mw(z,xt),I.reversedDepthBuffer&&_&&E.buffers.depth.setReversed(!0),pe=z.createFramebuffer(),ge=z.createFramebuffer(),K=z.createFramebuffer(),X=new R1(z),se=new tw,me=new gw(z,xt,E,se,I,Be,X),Ne=new T1(j),Oe=new LE(z),ke=new g1(z,Oe),_e=new C1(z,Oe,X,ke),he=new N1(z,_e,Oe,ke,X),Z=new D1(z,I,me),Qe=new x1(se),Le=new ew(j,Ne,xt,I,ke,Qe),je=new bw(j,se),ze=new iw,Fe=new cw(xt),pt=new m1(j,Ne,E,he,T,m),Je=new pw(j,he,I),q=new Ew(z,X,I,E),Pe=new _1(z,xt,X),Se=new w1(z,xt,X),X.programs=Le.programs,j.capabilities=I,j.extensions=xt,j.properties=se,j.renderLists=ze,j.shadowMap=Je,j.state=E,j.info=X}Me(),C!==Ei&&(L=new L1(C,i.width,i.height,p,l,c));const De=new Sw(j,z);this.xr=De,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){const w=xt.get("WEBGL_lose_context");w&&w.loseContext()},this.forceContextRestore=function(){const w=xt.get("WEBGL_lose_context");w&&w.restoreContext()},this.getPixelRatio=function(){return Ee},this.setPixelRatio=function(w){w!==void 0&&(Ee=w,this.setSize(ae,Ae,!1))},this.getSize=function(w){return w.set(ae,Ae)},this.setSize=function(w,Q,fe=!0){if(De.isPresenting){_t("WebGLRenderer: Can't change size while VR device is presenting.");return}ae=w,Ae=Q,i.width=Math.floor(w*Ee),i.height=Math.floor(Q*Ee),fe===!0&&(i.style.width=w+"px",i.style.height=Q+"px"),L!==null&&L.setSize(i.width,i.height),this.setViewport(0,0,w,Q)},this.getDrawingBufferSize=function(w){return w.set(ae*Ee,Ae*Ee).floor()},this.setDrawingBufferSize=function(w,Q,fe){ae=w,Ae=Q,Ee=fe,i.width=Math.floor(w*fe),i.height=Math.floor(Q*fe),this.setViewport(0,0,w,Q)},this.setEffects=function(w){if(C===Ei){jt("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(w){for(let Q=0;Q{function Xe(){if(ce.forEach(function(Ze){se.get(Ze).currentProgram.isReady()&&ce.delete(Ze)}),ce.size===0){ue(w);return}setTimeout(Xe,10)}xt.get("KHR_parallel_shader_compile")!==null?Xe():setTimeout(Xe,10)})};let ja=null;function re(w){ja&&ja(w)}function we(){it.stop()}function Ge(){it.start()}const it=new ey;it.setAnimationLoop(re),typeof self<"u"&&it.setContext(self),this.setAnimationLoop=function(w){ja=w,De.setAnimationLoop(w),w===null?it.stop():it.start()},De.addEventListener("sessionstart",we),De.addEventListener("sessionend",Ge),this.render=function(w,Q){if(Q!==void 0&&Q.isCamera!==!0){jt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(V===!0)return;$!==null&&$.renderStart(w,Q);const fe=De.enabled===!0&&De.isPresenting===!0,ce=L!==null&&(ne===null||fe)&&L.begin(j,ne);if(w.matrixWorldAutoUpdate===!0&&w.updateMatrixWorld(),Q.parent===null&&Q.matrixWorldAutoUpdate===!0&&Q.updateMatrixWorld(),De.enabled===!0&&De.isPresenting===!0&&(L===null||L.isCompositing()===!1)&&(De.cameraAutoUpdate===!0&&De.updateCamera(Q),Q=De.getCamera()),w.isScene===!0&&w.onBeforeRender(j,w,Q,ne),U=Fe.get(w,A.length),U.init(Q),U.state.textureUnits=me.getTextureUnits(),A.push(U),Mt.multiplyMatrices(Q.projectionMatrix,Q.matrixWorldInverse),Et.setFromProjectionMatrix(Mt,sa,Q.reversedDepth),St=this.localClippingEnabled,yt=Qe.init(this.clippingPlanes,St),O=ze.get(w,N.length),O.init(),N.push(O),De.enabled===!0&&De.isPresenting===!0){const Ze=j.xr.getDepthSensingMesh();Ze!==null&<(Ze,Q,-1/0,j.sortObjects)}lt(w,Q,0,j.sortObjects),O.finish(),j.sortObjects===!0&&O.sort(He,nt,Q.reversedDepth),It=De.enabled===!1||De.isPresenting===!1||De.hasDepthSensing()===!1,It&&pt.addToRenderList(O,w),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),yt===!0&&Qe.beginShadows();const ue=U.state.shadowsArray;if(Je.render(ue,w,Q),yt===!0&&Qe.endShadows(),(ce&&L.hasRenderPass())===!1){const Ze=O.opaque,Ve=O.transmissive;if(U.setupLights(),Q.isArrayCamera){const et=Q.cameras;if(Ve.length>0)for(let $e=0,ct=et.length;$e0&&In(Ze,Ve,w,Q),It&&pt.render(w),vt(O,w,Q)}ne!==null&&G===0&&(me.updateMultisampleRenderTarget(ne),me.updateRenderTargetMipmap(ne)),ce&&L.end(j),w.isScene===!0&&w.onAfterRender(j,w,Q),ke.resetDefaultState(),ye=-1,xe=null,A.pop(),A.length>0?(U=A[A.length-1],me.setTextureUnits(U.state.textureUnits),yt===!0&&Qe.setGlobalState(j.clippingPlanes,U.state.camera)):U=null,N.pop(),N.length>0?O=N[N.length-1]:O=null,$!==null&&$.renderEnd()};function lt(w,Q,fe,ce){if(w.visible===!1)return;if(w.layers.test(Q.layers)){if(w.isGroup)fe=w.renderOrder;else if(w.isLOD)w.autoUpdate===!0&&w.update(Q);else if(w.isLightProbeGrid)U.pushLightProbeGrid(w);else if(w.isLight)U.pushLight(w),w.castShadow&&U.pushShadow(w);else if(w.isSprite){if(!w.frustumCulled||Et.intersectsSprite(w)){ce&&Gt.setFromMatrixPosition(w.matrixWorld).applyMatrix4(Mt);const Ze=he.update(w),Ve=w.material;Ve.visible&&O.push(w,Ze,Ve,fe,Gt.z,null)}}else if((w.isMesh||w.isLine||w.isPoints)&&(!w.frustumCulled||Et.intersectsObject(w))){const Ze=he.update(w),Ve=w.material;if(ce&&(w.boundingSphere!==void 0?(w.boundingSphere===null&&w.computeBoundingSphere(),Gt.copy(w.boundingSphere.center)):(Ze.boundingSphere===null&&Ze.computeBoundingSphere(),Gt.copy(Ze.boundingSphere.center)),Gt.applyMatrix4(w.matrixWorld).applyMatrix4(Mt)),Array.isArray(Ve)){const et=Ze.groups;for(let $e=0,ct=et.length;$e0&&Zt(ue,Q,fe),Xe.length>0&&Zt(Xe,Q,fe),Ze.length>0&&Zt(Ze,Q,fe),E.buffers.depth.setTest(!0),E.buffers.depth.setMask(!0),E.buffers.color.setMask(!0),E.setPolygonOffset(!1)}function In(w,Q,fe,ce){if((fe.isScene===!0?fe.overrideMaterial:null)!==null)return;if(U.state.transmissionRenderTarget[ce.id]===void 0){const ot=xt.has("EXT_color_buffer_half_float")||xt.has("EXT_color_buffer_float");U.state.transmissionRenderTarget[ce.id]=new oa(1,1,{generateMipmaps:!0,type:ot?Ha:Ei,minFilter:Js,samples:Math.max(4,I.samples),stencilBuffer:c,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:kt.workingColorSpace})}const Xe=U.state.transmissionRenderTarget[ce.id],Ze=ce.viewport||F;Xe.setSize(Ze.z*j.transmissionResolutionScale,Ze.w*j.transmissionResolutionScale);const Ve=j.getRenderTarget(),et=j.getActiveCubeFace(),$e=j.getActiveMipmapLevel();j.setRenderTarget(Xe),j.getClearColor(Ue),Ie=j.getClearAlpha(),Ie<1&&j.setClearColor(16777215,.5),j.clear(),It&&pt.render(fe);const ct=j.toneMapping;j.toneMapping=ra;const Ct=ce.viewport;if(ce.viewport!==void 0&&(ce.viewport=void 0),U.setupLightsView(ce),yt===!0&&Qe.setGlobalState(j.clippingPlanes,ce),Zt(w,fe,ce),me.updateMultisampleRenderTarget(Xe),me.updateRenderTargetMipmap(Xe),xt.has("WEBGL_multisampled_render_to_texture")===!1){let ot=!1;for(let Xt=0,gn=Q.length;Xt0,ce.currentProgram=Ct,ce.uniformsList=null,Ct}function fn(w){if(w.uniformsList===null){const Q=w.currentProgram.getUniforms();w.uniformsList=Mu.seqWithValue(Q.seq,w.uniforms)}return w.uniformsList}function Gn(w,Q){const fe=se.get(w);fe.outputColorSpace=Q.outputColorSpace,fe.batching=Q.batching,fe.batchingColor=Q.batchingColor,fe.instancing=Q.instancing,fe.instancingColor=Q.instancingColor,fe.instancingMorph=Q.instancingMorph,fe.skinning=Q.skinning,fe.morphTargets=Q.morphTargets,fe.morphNormals=Q.morphNormals,fe.morphColors=Q.morphColors,fe.morphTargetsCount=Q.morphTargetsCount,fe.numClippingPlanes=Q.numClippingPlanes,fe.numIntersection=Q.numClipIntersection,fe.vertexAlphas=Q.vertexAlphas,fe.vertexTangents=Q.vertexTangents,fe.toneMapping=Q.toneMapping}function Bn(w,Q){if(w.length===0)return null;if(w.length===1)return w[0].texture!==null?w[0]:null;D.setFromMatrixPosition(Q.matrixWorld);for(let fe=0,ce=w.length;fe0),ot=!!fe.morphAttributes.position,Xt=!!fe.morphAttributes.normal,gn=!!fe.morphAttributes.color;let cn=ra;ce.toneMapped&&(ne===null||ne.isXRRenderTarget===!0)&&(cn=j.toneMapping);const Qt=fe.morphAttributes.position||fe.morphAttributes.normal||fe.morphAttributes.color,Jt=Qt!==void 0?Qt.length:0,qe=se.get(ce),qn=U.state.lights;if(yt===!0&&(St===!0||w!==xe)){const $t=w===xe&&ce.id===ye;Qe.setState(ce,w,$t)}let Ut=!1;ce.version===qe.__version?(qe.needsLights&&qe.lightsStateVersion!==qn.state.version||qe.outputColorSpace!==Ve||ue.isBatchedMesh&&qe.batching===!1||!ue.isBatchedMesh&&qe.batching===!0||ue.isBatchedMesh&&qe.batchingColor===!0&&ue.colorTexture===null||ue.isBatchedMesh&&qe.batchingColor===!1&&ue.colorTexture!==null||ue.isInstancedMesh&&qe.instancing===!1||!ue.isInstancedMesh&&qe.instancing===!0||ue.isSkinnedMesh&&qe.skinning===!1||!ue.isSkinnedMesh&&qe.skinning===!0||ue.isInstancedMesh&&qe.instancingColor===!0&&ue.instanceColor===null||ue.isInstancedMesh&&qe.instancingColor===!1&&ue.instanceColor!==null||ue.isInstancedMesh&&qe.instancingMorph===!0&&ue.morphTexture===null||ue.isInstancedMesh&&qe.instancingMorph===!1&&ue.morphTexture!==null||qe.envMap!==$e||ce.fog===!0&&qe.fog!==Xe||qe.numClippingPlanes!==void 0&&(qe.numClippingPlanes!==Qe.numPlanes||qe.numIntersection!==Qe.numIntersection)||qe.vertexAlphas!==ct||qe.vertexTangents!==Ct||qe.morphTargets!==ot||qe.morphNormals!==Xt||qe.morphColors!==gn||qe.toneMapping!==cn||qe.morphTargetsCount!==Jt||!!qe.lightProbeGrid!=U.state.lightProbeGridArray.length>0)&&(Ut=!0):(Ut=!0,qe.__version=ce.version);let Dn=qe.currentProgram;Ut===!0&&(Dn=yn(ce,Q,ue),$&&ce.isNodeMaterial&&$.onUpdateProgram(ce,Dn,qe));let di=!1,zi=!1,hi=!1;const en=Dn.getUniforms(),_n=qe.uniforms;if(E.useProgram(Dn.program)&&(di=!0,zi=!0,hi=!0),ce.id!==ye&&(ye=ce.id,zi=!0),qe.needsLights){const $t=Bn(U.state.lightProbeGridArray,ue);qe.lightProbeGrid!==$t&&(qe.lightProbeGrid=$t,zi=!0)}if(di||xe!==w){E.buffers.depth.getReversed()&&w.reversedDepth!==!0&&(w._reversedDepth=!0,w.updateProjectionMatrix()),en.setValue(z,"projectionMatrix",w.projectionMatrix),en.setValue(z,"viewMatrix",w.matrixWorldInverse);const $i=en.map.cameraPosition;$i!==void 0&&$i.setValue(z,Ht.setFromMatrixPosition(w.matrixWorld)),I.logarithmicDepthBuffer&&en.setValue(z,"logDepthBufFC",2/(Math.log(w.far+1)/Math.LN2)),(ce.isMeshPhongMaterial||ce.isMeshToonMaterial||ce.isMeshLambertMaterial||ce.isMeshBasicMaterial||ce.isMeshStandardMaterial||ce.isShaderMaterial)&&en.setValue(z,"isOrthographic",w.isOrthographicCamera===!0),xe!==w&&(xe=w,zi=!0,hi=!0)}if(qe.needsLights&&(qn.state.directionalShadowMap.length>0&&en.setValue(z,"directionalShadowMap",qn.state.directionalShadowMap,me),qn.state.spotShadowMap.length>0&&en.setValue(z,"spotShadowMap",qn.state.spotShadowMap,me),qn.state.pointShadowMap.length>0&&en.setValue(z,"pointShadowMap",qn.state.pointShadowMap,me)),ue.isSkinnedMesh){en.setOptional(z,ue,"bindMatrix"),en.setOptional(z,ue,"bindMatrixInverse");const $t=ue.skeleton;$t&&($t.boneTexture===null&&$t.computeBoneTexture(),en.setValue(z,"boneTexture",$t.boneTexture,me))}ue.isBatchedMesh&&(en.setOptional(z,ue,"batchingTexture"),en.setValue(z,"batchingTexture",ue._matricesTexture,me),en.setOptional(z,ue,"batchingIdTexture"),en.setValue(z,"batchingIdTexture",ue._indirectTexture,me),en.setOptional(z,ue,"batchingColorTexture"),ue._colorsTexture!==null&&en.setValue(z,"batchingColorTexture",ue._colorsTexture,me));const Hi=fe.morphAttributes;if((Hi.position!==void 0||Hi.normal!==void 0||Hi.color!==void 0)&&Z.update(ue,fe,Dn),(zi||qe.receiveShadow!==ue.receiveShadow)&&(qe.receiveShadow=ue.receiveShadow,en.setValue(z,"receiveShadow",ue.receiveShadow)),(ce.isMeshStandardMaterial||ce.isMeshLambertMaterial||ce.isMeshPhongMaterial)&&ce.envMap===null&&Q.environment!==null&&(_n.envMapIntensity.value=Q.environmentIntensity),_n.dfgLUT!==void 0&&(_n.dfgLUT.value=Aw()),zi){if(en.setValue(z,"toneMappingExposure",j.toneMappingExposure),qe.needsLights&&Kt(_n,hi),Xe&&ce.fog===!0&&je.refreshFogUniforms(_n,Xe),je.refreshMaterialUniforms(_n,ce,Ee,Ae,U.state.transmissionRenderTarget[w.id]),qe.needsLights&&qe.lightProbeGrid){const $t=qe.lightProbeGrid;_n.probesSH.value=$t.texture,_n.probesMin.value.copy($t.boundingBox.min),_n.probesMax.value.copy($t.boundingBox.max),_n.probesResolution.value.copy($t.resolution)}Mu.upload(z,fn(qe),_n,me)}if(ce.isShaderMaterial&&ce.uniformsNeedUpdate===!0&&(Mu.upload(z,fn(qe),_n,me),ce.uniformsNeedUpdate=!1),ce.isSpriteMaterial&&en.setValue(z,"center",ue.center),en.setValue(z,"modelViewMatrix",ue.modelViewMatrix),en.setValue(z,"normalMatrix",ue.normalMatrix),en.setValue(z,"modelMatrix",ue.matrixWorld),ce.uniformsGroups!==void 0){const $t=ce.uniformsGroups;for(let $i=0,Xa=$t.length;$i0&&me.useMultisampledRTT(w)===!1?ce=se.get(w).__webglMultisampledFramebuffer:Array.isArray($e)?ce=$e[fe]:ce=$e,F.copy(w.viewport),J.copy(w.scissor),Ce=w.scissorTest}else F.copy(Ke).multiplyScalar(Ee).floor(),J.copy(zt).multiplyScalar(Ee).floor(),Ce=ht;if(fe!==0&&(ce=pe),E.bindFramebuffer(z.FRAMEBUFFER,ce)&&E.drawBuffers(w,ce),E.viewport(F),E.scissor(J),E.setScissorTest(Ce),ue){const Ve=se.get(w.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+Q,Ve.__webglTexture,fe)}else if(Xe){const Ve=Q;for(let et=0;et1&&z.readBuffer(z.COLOR_ATTACHMENT0+Ve),!I.textureFormatReadable(ct)){jt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!I.textureTypeReadable(Ct)){jt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}Q>=0&&Q<=w.width-ce&&fe>=0&&fe<=w.height-ue&&z.readPixels(Q,fe,ce,ue,Be.convert(ct),Be.convert(Ct),Xe)}finally{const $e=ne!==null?se.get(ne).__webglFramebuffer:null;E.bindFramebuffer(z.FRAMEBUFFER,$e)}}},this.readRenderTargetPixelsAsync=async function(w,Q,fe,ce,ue,Xe,Ze,Ve=0){if(!(w&&w.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let et=se.get(w).__webglFramebuffer;if(w.isWebGLCubeRenderTarget&&Ze!==void 0&&(et=et[Ze]),et)if(Q>=0&&Q<=w.width-ce&&fe>=0&&fe<=w.height-ue){E.bindFramebuffer(z.FRAMEBUFFER,et);const $e=w.textures[Ve],ct=$e.format,Ct=$e.type;if(w.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+Ve),!I.textureFormatReadable(ct))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!I.textureTypeReadable(Ct))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const ot=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,ot),z.bufferData(z.PIXEL_PACK_BUFFER,Xe.byteLength,z.STREAM_READ),z.readPixels(Q,fe,ce,ue,Be.convert(ct),Be.convert(Ct),0);const Xt=ne!==null?se.get(ne).__webglFramebuffer:null;E.bindFramebuffer(z.FRAMEBUFFER,Xt);const gn=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await zb(z,gn,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,ot),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,Xe),z.deleteBuffer(ot),z.deleteSync(gn),Xe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(w,Q=null,fe=0){const ce=Math.pow(2,-fe),ue=Math.floor(w.image.width*ce),Xe=Math.floor(w.image.height*ce),Ze=Q!==null?Q.x:0,Ve=Q!==null?Q.y:0;me.setTexture2D(w,0),z.copyTexSubImage2D(z.TEXTURE_2D,fe,0,0,Ze,Ve,ue,Xe),E.unbindTexture()},this.copyTextureToTexture=function(w,Q,fe=null,ce=null,ue=0,Xe=0){let Ze,Ve,et,$e,ct,Ct,ot,Xt,gn;const cn=w.isCompressedTexture?w.mipmaps[Xe]:w.image;if(fe!==null)Ze=fe.max.x-fe.min.x,Ve=fe.max.y-fe.min.y,et=fe.isBox3?fe.max.z-fe.min.z:1,$e=fe.min.x,ct=fe.min.y,Ct=fe.isBox3?fe.min.z:0;else{const _n=Math.pow(2,-ue);Ze=Math.floor(cn.width*_n),Ve=Math.floor(cn.height*_n),w.isDataArrayTexture?et=cn.depth:w.isData3DTexture?et=Math.floor(cn.depth*_n):et=1,$e=0,ct=0,Ct=0}ce!==null?(ot=ce.x,Xt=ce.y,gn=ce.z):(ot=0,Xt=0,gn=0);const Qt=Be.convert(Q.format),Jt=Be.convert(Q.type);let qe;Q.isData3DTexture?(me.setTexture3D(Q,0),qe=z.TEXTURE_3D):Q.isDataArrayTexture||Q.isCompressedArrayTexture?(me.setTexture2DArray(Q,0),qe=z.TEXTURE_2D_ARRAY):(me.setTexture2D(Q,0),qe=z.TEXTURE_2D),E.activeTexture(z.TEXTURE0),E.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,Q.flipY),E.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Q.premultiplyAlpha),E.pixelStorei(z.UNPACK_ALIGNMENT,Q.unpackAlignment);const qn=E.getParameter(z.UNPACK_ROW_LENGTH),Ut=E.getParameter(z.UNPACK_IMAGE_HEIGHT),Dn=E.getParameter(z.UNPACK_SKIP_PIXELS),di=E.getParameter(z.UNPACK_SKIP_ROWS),zi=E.getParameter(z.UNPACK_SKIP_IMAGES);E.pixelStorei(z.UNPACK_ROW_LENGTH,cn.width),E.pixelStorei(z.UNPACK_IMAGE_HEIGHT,cn.height),E.pixelStorei(z.UNPACK_SKIP_PIXELS,$e),E.pixelStorei(z.UNPACK_SKIP_ROWS,ct),E.pixelStorei(z.UNPACK_SKIP_IMAGES,Ct);const hi=w.isDataArrayTexture||w.isData3DTexture,en=Q.isDataArrayTexture||Q.isData3DTexture;if(w.isDepthTexture){const _n=se.get(w),Hi=se.get(Q),$t=se.get(_n.__renderTarget),$i=se.get(Hi.__renderTarget);E.bindFramebuffer(z.READ_FRAMEBUFFER,$t.__webglFramebuffer),E.bindFramebuffer(z.DRAW_FRAMEBUFFER,$i.__webglFramebuffer);for(let Xa=0;XaMath.PI&&(s-=li),l<-Math.PI?l+=li:l>Math.PI&&(l-=li),s<=l?this._spherical.theta=Math.max(s,Math.min(l,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(s+l)/2?Math.max(s,this._spherical.theta):Math.min(l,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let c=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const f=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),c=f!=this._spherical.radius}if(Un.setFromSpherical(this._spherical),Un.applyQuaternion(this._quatInverse),i.copy(this.target).add(Un),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let f=null;if(this.object.isPerspectiveCamera){const p=Un.length();f=this._clampDistance(p*this._scale);const m=p-f;this.object.position.addScaledVector(this._dollyDirection,m),this.object.updateMatrixWorld(),c=!!m}else if(this.object.isOrthographicCamera){const p=new ie(this._mouse.x,this._mouse.y,0);p.unproject(this.object);const m=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),c=m!==this.object.zoom;const h=new ie(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(p),this.object.updateMatrixWorld(),f=Un.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;f!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(f).add(this.object.position):(gu.origin.copy(this.object.position),gu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(gu.direction))Dh||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Dh||this._lastTargetPosition.distanceToSquared(this.target)>Dh?(this.dispatchEvent(ix),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?li/60*this.autoRotateSpeed*e:li/60/60*this.autoRotateSpeed}_getZoomScale(e){const i=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*i)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,i){Un.setFromMatrixColumn(i,0),Un.multiplyScalar(-e),this._panOffset.add(Un)}_panUp(e,i){this.screenSpacePanning===!0?Un.setFromMatrixColumn(i,1):(Un.setFromMatrixColumn(i,0),Un.crossVectors(this.object.up,Un)),Un.multiplyScalar(e),this._panOffset.add(Un)}_pan(e,i){const s=this.domElement;if(this.object.isPerspectiveCamera){const l=this.object.position;Un.copy(l).sub(this.target);let c=Un.length();c*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*c/s.clientHeight,this.object.matrix),this._panUp(2*i*c/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(i*(this.object.top-this.object.bottom)/this.object.zoom/s.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,i){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const s=this.domElement.getBoundingClientRect(),l=e-s.left,c=i-s.top,f=s.width,p=s.height;this._mouse.x=l/f*2-1,this._mouse.y=-(c/p)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const i=this.domElement;this._rotateLeft(li*this._rotateDelta.x/i.clientHeight),this._rotateUp(li*this._rotateDelta.y/i.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let i=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(li*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),i=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-li*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),i=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(li*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),i=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-li*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),i=!0;break}i&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),l=.5*(e.pageY+i.y);this._rotateStart.set(s,l)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),l=.5*(e.pageY+i.y);this._panStart.set(s,l)}}_handleTouchStartDolly(e){const i=this._getSecondPointerPosition(e),s=e.pageX-i.x,l=e.pageY-i.y,c=Math.sqrt(s*s+l*l);this._dollyStart.set(0,c)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const s=this._getSecondPointerPosition(e),l=.5*(e.pageX+s.x),c=.5*(e.pageY+s.y);this._rotateEnd.set(l,c)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const i=this.domElement;this._rotateLeft(li*this._rotateDelta.x/i.clientHeight),this._rotateUp(li*this._rotateDelta.y/i.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),l=.5*(e.pageY+i.y);this._panEnd.set(s,l)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const i=this._getSecondPointerPosition(e),s=e.pageX-i.x,l=e.pageY-i.y,c=Math.sqrt(s*s+l*l);this._dollyEnd.set(0,c),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const f=(e.pageX+i.x)*.5,p=(e.pageY+i.y)*.5;this._updateZoomParameters(f,p)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let i=0;i1?e.y/(i-1):.5,f=i>1?e.z/(i-1):.5,p=Sl((e.state??1)/6,0,1);if(l.copy(a.primaryColor).lerp(a.accentColor,Sl(c*.42+p*.5,0,1)),s==="lattice-gas-3d"||s==="snake-3d"){l.lerp(new dt("#ffffff"),Sl(p*.22+f*.08,0,.34)),l.multiplyScalar(1+p*.16);return}s==="generations-3d"&&l.lerp(new dt("#94a3b8"),p*.22),l.lerp(new dt("#ffffff"),Sl(f*.18,0,.24)),l.offsetHSL(0,0,.05+f*.1)}function Zw(a,e,i,s,l){cy(a.mesh),a.mesh=qw(i,l),a.scene.add(a.mesh);const c=a.mesh,f=new Ln,p=new dt,m=Es/i,h=-Es/2+m/2;let y=0;for(const S of e){if(y>=c.count)break;S.x<0||S.y<0||S.z<0||S.x>=i||S.y>=i||S.z>=i||(f.position.set(h+S.x*m,h+S.y*m,h+S.z*m),f.rotation.set(0,0,0),f.updateMatrix(),Yw(a,S,i,s,p),c.setMatrixAt(y,f.matrix),c.setColorAt(y,p),y+=1)}c.count=y,c.instanceMatrix.needsUpdate=!0,c.instanceColor&&(c.instanceColor.needsUpdate=!0)}function Kw(a,e){const i=new nE;i.background=new dt("#061006");const s=new Ii(42,1,.1,300);s.position.set(sx,Vw,sx);const l=new Cw({antialias:!0,alpha:!0});l.setPixelRatio(Math.min(window.devicePixelRatio,2)),l.shadowMap.enabled=!0,l.shadowMap.type=Ax,l.outputColorSpace=bi,l.toneMapping=Lp,l.toneMappingExposure=1.12,a.appendChild(l.domElement);const c=new Rw(s,l.domElement);c.enableDamping=!0,c.dampingFactor=.06,c.minDistance=12,c.maxDistance=60,c.target.set(0,0,0),i.add(new CE("#f5efb7",.42)),i.add(new EE("#f5efb7","#061006",.96));const f=new Dv("#fff3a8",1.25);f.position.set(18,28,14),f.target.position.set(0,0,0),i.add(f),i.add(f.target);const p=new Dv(e.accentColor,.46);p.position.set(-24,18,-12),i.add(p);const m=jw(e);i.add(m);const h=Xw(e);i.add(h);const y={animationFrame:0,bounds:m,grid:h,mesh:null,primaryColor:new dt(e.primaryColor),accentColor:new dt(e.accentColor),resizeObserver:new ResizeObserver(()=>S()),scene:i};function S(){const T=Math.max(a.clientWidth,1),C=Math.max(a.clientHeight,1);s.aspect=T/C,s.updateProjectionMatrix(),l.setSize(T,C,!1)}function _(){c.update(),l.render(i,s)}function b(){_(),y.animationFrame=window.requestAnimationFrame(b)}return y.resizeObserver.observe(a),S(),b(),{dispose(){window.cancelAnimationFrame(y.animationFrame),y.resizeObserver.disconnect(),cy(y.mesh),y.bounds.geometry.dispose(),Tp(y.bounds.material),y.grid.geometry.dispose(),Tp(y.grid.material),c.dispose(),l.dispose(),l.domElement.parentNode===a&&a.removeChild(l.domElement)},render:_,update(T){Ww(y,T.options),Zw(y,T.cells,T.size,T.ruleId,T.options),_()}}}function $w(a){const e=a.simulation?.grid?.size;if(!Array.isArray(e))return 16;const i=e[0];return typeof i=="number"?Math.min(30,Math.max(8,Math.round(i))):16}function Qw(a){const e=a.simulation?.ruleId;return typeof e=="string"&&e.endsWith("-3d")?e:"life-3d"}function Jw(a){const e=a.renderer??{};return{accentColor:typeof e.accentColor=="string"?e.accentColor:"#f0c94a",cellGap:typeof e.cellGap=="number"?e.cellGap:.14,primaryColor:typeof e.primaryColor=="string"?e.primaryColor:"#70f45f",showBounds:typeof e.showBounds=="boolean"?e.showBounds:!0}}function eR(a){const e=a.simulation?.initialCondition?.cells;return Array.isArray(e)?e.flatMap(i=>{const[s,l,c=0,f=1]=i;return!Number.isInteger(s)||!Number.isInteger(l)||!Number.isInteger(c)?[]:[{x:s,y:l,z:c,state:typeof f=="number"?f:1}]}):[]}function tR({caption:a,settings:e}){const i=ee.useRef(null),s=ee.useRef(null),l=ee.useMemo(()=>eR(e),[e]),c=$w(e),f=Qw(e),p=ee.useMemo(()=>Jw(e),[e]);return ee.useEffect(()=>{const m=i.current;if(!m)return;const h=Kw(m,p);return s.current=h,h.update({cells:l,options:p,ruleId:f,size:c}),()=>{h.dispose(),s.current=null}},[]),ee.useEffect(()=>{s.current?.update({cells:l,options:p,ruleId:f,size:c})},[l,p,f,c]),g.jsxs("div",{className:"board-wrap voxel-renderer-wrap",children:[a.trim()?g.jsx("div",{className:"renderer-caption",children:a}):null,g.jsx("div",{className:"studio-voxel-viewport",ref:i}),l.length===0?g.jsx("div",{className:"voxel-empty-hint",children:"No voxel initial condition on this node"}):null]})}const Rl=new Map;function Bu(a,e={}){if(!a.id.trim())throw new Error("CA renderer runtime id is required");if(Rl.has(a.id)&&!e.replace)throw new Error(`CA renderer runtime already registered: ${a.id}`);Rl.set(a.id,a)}function nR(){return[...Rl.values()]}function Nh(a){return nR().filter(e=>Oa(e,a))}function iR(a){return Rl.get(a)??[...Rl.values()].find(e=>e.aliases?.includes(a))??null}function Fu({caption:a,cells:e,settings:i,onCellsChange:s}){const l=i.renderer?.id??"2d-canvas",c=iR(l),f=Ml(i);if(c&&(!f||Oa(c,f))){const p=c.Component;return g.jsx(p,{caption:a,cells:e,settings:i,onCellsChange:s})}return g.jsxs("div",{className:"board-wrap",children:[a.trim()?g.jsx("div",{className:"renderer-caption",children:a}):null,g.jsx("div",{className:"renderer-empty",children:c?`Renderer ${l} does not support this CA space`:`Renderer unavailable: ${l}`})]})}function aR({caption:a,settings:e}){return g.jsx(tR,{caption:a,settings:e})}function sR(a,e,i,s){return typeof a=="number"&&Number.isFinite(a)?Math.max(i,Math.min(s,a)):e}function rR(a){const e=a.renderer?.elementaryRule;if(typeof e=="number")return Math.max(0,Math.min(255,Math.floor(e)));const i=a.simulation?.ruleId??"",s=/(?:rule[-_\s]*)?(\d{1,3})/i.exec(i);return s?Math.max(0,Math.min(255,Number(s[1]))):110}function oR(a,e){return a.map((i,s)=>{const l=a[(s-1+a.length)%a.length]?1:0,c=a[s]?1:0,f=a[(s+1)%a.length]?1:0,p=l<<2|c<<1|f;return(e>>p&1)===1})}function lR(a){const e=a.findIndex(i=>i.some(Boolean));return e===-1?0:e}function cR({caption:a,cells:e,onCellsChange:i}){const s=ee.useRef(null),l=ee.useRef(e),c=ee.useRef(null),[f,p]=ee.useState(0),m=e[0]?.length??0,h=e.length;ee.useEffect(()=>{l.current=e},[e]),ee.useEffect(()=>{const C=s.current;if(!C)return;const v=new ResizeObserver(()=>p(x=>x+1));return v.observe(C),()=>v.disconnect()},[]),ee.useEffect(()=>{const C=s.current;if(!C||m===0||h===0)return;const v=C.getContext("2d");if(!v)return;const x=C.getBoundingClientRect(),B=window.devicePixelRatio||1,P=Math.max(1,Math.floor(x.width*B)),D=Math.max(1,Math.floor(x.height*B));(C.width!==P||C.height!==D)&&(C.width=P,C.height=D),v.setTransform(B,0,0,B,0,0),v.clearRect(0,0,x.width,x.height),v.fillStyle="#071206",v.fillRect(0,0,x.width,x.height);const O=Math.min(x.width/m,x.height/h),U=O*m,N=O*h,A=(x.width-U)/2,L=(x.height-N)/2,j=Math.max(1,Math.min(2,O*.08));v.strokeStyle="#1e3519",v.lineWidth=1;for(let V=0;V=m||A>=h?null:{x:N,y:A}}function S(C,v,x){const B=l.current;if(B[v]?.[C]===x)return;const P=B.map((D,O)=>O===v?D.map((U,N)=>N===C?x:U):D);l.current=P,i(P)}function _(C){const v=y(C);if(!v)return;C.currentTarget.setPointerCapture(C.pointerId);const x=!l.current[v.y][v.x];c.current=x,S(v.x,v.y,x)}function b(C){if(c.current===null)return;const v=y(C);v&&S(v.x,v.y,c.current)}function T(C){c.current=null,C.currentTarget.hasPointerCapture(C.pointerId)&&C.currentTarget.releasePointerCapture(C.pointerId)}return g.jsxs("div",{className:"board-wrap",children:[a.trim()?g.jsx("div",{className:"renderer-caption",children:a}):null,g.jsx("canvas",{ref:s,"aria-label":"Game of Life cell editor",className:"board-canvas",role:"img",onPointerCancel:T,onPointerDown:_,onPointerLeave:T,onPointerMove:b,onPointerUp:T})]})}function uR({caption:a,cells:e,settings:i,onCellsChange:s}){const l=ee.useRef(null),c=ee.useRef(e),[f,p]=ee.useState(0),m=e[0]?.length??0,h=Math.min(e.length-1,Math.max(0,lR(e))),y=e[h]??[],S=rR(i),_=sR(i.renderer?.historyRows,96,8,512);ee.useEffect(()=>{c.current=e},[e]),ee.useEffect(()=>{const T=l.current;if(!T)return;const C=new ResizeObserver(()=>p(v=>v+1));return C.observe(T),()=>C.disconnect()},[]),ee.useEffect(()=>{const T=l.current;if(!T||m===0||y.length===0)return;const C=T.getContext("2d");if(!C)return;const v=T.getBoundingClientRect(),x=window.devicePixelRatio||1,B=Math.max(1,Math.floor(v.width*x)),P=Math.max(1,Math.floor(v.height*x));(T.width!==B||T.height!==P)&&(T.width=B,T.height=P),C.setTransform(x,0,0,x,0,0),C.clearRect(0,0,v.width,v.height),C.fillStyle="#061006",C.fillRect(0,0,v.width,v.height);const D=v.width/m,O=v.height/_;let U=[...y];for(let N=0;N<_;N+=1){const A=N/Math.max(1,_-1);for(let L=0;L=m)return;const P=c.current.map((D,O)=>O===h?D.map((U,N)=>N===x?!U:U):D);c.current=P,s(P)}return g.jsxs("div",{className:"board-wrap elementary-renderer-wrap",children:[a.trim()?g.jsx("div",{className:"renderer-caption",children:a}):null,g.jsx("canvas",{ref:l,"aria-label":`Elementary cellular automaton rule ${S}`,className:"elementary-canvas",role:"img",onPointerDown:b})]})}function fR({caption:a,cells:e,onCellsChange:i}){const s=ee.useRef(null),l=ee.useRef(e),c=ee.useRef(null),[f,p]=ee.useState(0),m=e[0]?.length??0,h=e.length;ee.useEffect(()=>{l.current=e},[e]),ee.useEffect(()=>{const C=s.current;if(!C)return;const v=new ResizeObserver(()=>p(x=>x+1));return v.observe(C),()=>v.disconnect()},[]),ee.useEffect(()=>{const C=s.current;if(!C||m===0||h===0)return;const v=C.getContext("2d");if(!v)return;const x=C.getBoundingClientRect(),B=window.devicePixelRatio||1,P=Math.max(1,Math.floor(x.width*B)),D=Math.max(1,Math.floor(x.height*B));(C.width!==P||C.height!==D)&&(C.width=P,C.height=D),v.setTransform(B,0,0,B,0,0),v.clearRect(0,0,x.width,x.height);const O=Math.min(x.width/m,x.height/h),U=O*m,N=O*h,A=(x.width-U)/2,L=(x.height-N)/2;v.fillStyle="#061006",v.fillRect(0,0,x.width,x.height);for(let j=0;j=m||A>=h?null:{x:N,y:A}}function S(C,v,x){const B=l.current;if(B[v]?.[C]===x)return;const P=B.map((D,O)=>O===v?D.map((U,N)=>N===C?x:U):D);l.current=P,i(P)}function _(C){const v=y(C);if(!v)return;C.currentTarget.setPointerCapture(C.pointerId);const x=!l.current[v.y][v.x];c.current=x,S(v.x,v.y,x)}function b(C){if(c.current===null)return;const v=y(C);v&&S(v.x,v.y,c.current)}function T(C){c.current=null,C.currentTarget.hasPointerCapture(C.pointerId)&&C.currentTarget.releasePointerCapture(C.pointerId)}return g.jsxs("div",{className:"board-wrap wildfire-renderer-wrap",children:[a.trim()?g.jsx("div",{className:"renderer-caption",children:a}):null,g.jsx("canvas",{ref:s,"aria-label":"Wildfire cellular automaton editor",className:"wildfire-canvas",role:"img",onPointerCancel:T,onPointerDown:_,onPointerLeave:T,onPointerMove:b,onPointerUp:T})]})}Bu({id:"2d-canvas",label:"2D Canvas",supportedClasses:[{dimensions:2,states:2}],Component:cR},{replace:!0});Bu({id:"elementary-1d",label:"Elementary 1D",aliases:["elementary-ca","1d-canvas"],supportedClasses:[{dimensions:1,states:2}],Component:uR},{replace:!0});Bu({id:"wildfire-2d",label:"Wildfire 2D",aliases:["forest-fire-2d"],supportedClasses:[{dimensions:2,states:2}],Component:fR},{replace:!0});Bu({id:"voxel-3d",label:"Voxel 3D",aliases:["three-voxel"],supportedClasses:[{dimensions:3,states:2}],Component:aR},{replace:!0});function dR(a,e){return a.sort_order-e.sort_order||a.name.localeCompare(e.name)}function hR(a){const e=new Map;for(const s of a){const l=e.get(s.parent_id)??[];l.push(s),e.set(s.parent_id,l)}function i(s){return(e.get(s)??[]).sort(dR).map(l=>({node:l,children:i(l.id)}))}return i(null)}function pR({assignedNodeId:a,nodes:e,selectedNodeId:i,onSelect:s}){const l=ee.useMemo(()=>hR(e),[e]);return l.length===0?g.jsx("p",{className:"empty",children:"This CA library has no presets."}):g.jsx("div",{className:"asset-tree",children:l.map(c=>g.jsx(uy,{assignedNodeId:a,item:c,selectedNodeId:i,onSelect:s},c.node.id))})}function uy({assignedNodeId:a,item:e,selectedNodeId:i,onSelect:s}){const[l,c]=ee.useState(!0),f=e.node.id===i,p=e.node.id===a;return g.jsxs("div",{className:"asset-tree-item",children:[g.jsxs("div",{className:`asset-tree-row${f?" selected":""}${p?" assigned":""}`,children:[g.jsx("button",{"aria-label":e.children.length?`${l?"Collapse":"Expand"} ${e.node.name}`:`${e.node.name} has no children`,className:"asset-tree-arrow",disabled:!e.children.length,type:"button",onClick:()=>c(m=>!m),children:e.children.length?l?"▾":"▸":"·"}),g.jsxs("button",{className:"asset-tree-select",type:"button",onClick:()=>s(e.node),children:[g.jsx("strong",{children:e.node.name}),g.jsxs("small",{children:[e.node.kind,p?" · current":""]}),e.node.description?g.jsx("span",{children:e.node.description}):null]})]}),l&&e.children.length?g.jsx("div",{className:"asset-tree-children",children:e.children.map(m=>g.jsx(uy,{assignedNodeId:a,item:m,selectedNodeId:i,onSelect:s},m.node.id))}):null]})}function ar(a){return!!a&&typeof a=="object"&&!Array.isArray(a)}function mR(a,e){return JSON.stringify(a)===JSON.stringify(e)}function Uh(a,e){let i=a;for(const s of e){if(!ar(i)||!(s in i))return;i=i[s]}return i}function gR(a,e){return a.join(".")==="simulation.initialCondition"&&ar(e)?`${Array.isArray(e.cells)?e.cells.length:0} live cells`:Array.isArray(e)?`${e.length} items`:ar(e)?"object":String(e)}function Kp(a,e){const i={...a};for(const[s,l]of Object.entries(e)){const c=i[s];i[s]=ar(c)&&ar(l)?Kp(c,l):l}return i}function _R(a,e){return a.sort_order-e.sort_order||a.name.localeCompare(e.name)||a.slug.localeCompare(e.slug)}function vR(a){const e=new Map;for(const s of a){const l=e.get(s.parent_id)??[];l.push(s),e.set(s.parent_id,l)}function i(s){const l=(e.get(s)??[]).sort(_R);return l.map((c,f)=>({node:c,children:i(c.id),siblingIndex:f,siblingCount:l.length}))}return i(null)}function fy(a,e,i={},s=null){const l=[];for(const c of a)if(l.push({item:c,inheritedParams:i,parentId:s}),e.has(c.node.id)){const f=Kp(i,c.node.params);l.push(...fy(c.children,e,f,c.node.id))}return l}function xR({assignedNodeId:a,engines:e=[],nodes:i,selectedNodeId:s,usedNodeIds:l,onCreateChild:c,onCreateGroup:f,onDelete:p,onMove:m,onRename:h,onSelect:y,onSet:S,onUnset:_}){const b=ee.useMemo(()=>vR(i),[i]),[T,C]=ee.useState(()=>new Set(i.map(N=>N.id))),[v,x]=ee.useState(""),[B,P]=ee.useState(""),D=ee.useMemo(()=>fy(b,T),[T,b]);ee.useEffect(()=>{C(N=>{const A=new Set([...N].filter(L=>i.some(j=>j.id===L)));for(const L of i)N.has(L.id)||A.add(L.id);return A})},[i]),ee.useEffect(()=>{if(!B)return;function N(L){const j=L.target;j instanceof Element&&(j.closest(".tree-node-action-menu")||j.closest(".node-action-trigger")||P(""))}function A(L){L.key==="Escape"&&P("")}return document.addEventListener("pointerdown",N),document.addEventListener("keydown",A),()=>{document.removeEventListener("pointerdown",N),document.removeEventListener("keydown",A)}},[B]);function O(N,A){C(L=>{const j=new Set(L);return A??!j.has(N)?j.add(N):j.delete(N),j})}function U(N){if(!["ArrowDown","ArrowUp","ArrowLeft","ArrowRight","Enter"].includes(N.key))return;const A=D.findIndex(({item:V})=>V.node.id===s),L=A===-1?0:A,j=D[L];if(j){if(N.key==="ArrowDown"||N.key==="ArrowUp"){N.preventDefault();const V=N.key==="ArrowDown"?1:-1,$=D[Math.min(Math.max(L+V,0),D.length-1)];$&&y($.item.node);return}if(N.key==="ArrowRight"){N.preventDefault(),j.item.children.length&&!T.has(j.item.node.id)?O(j.item.node.id,!0):j.item.children[0]&&y(j.item.children[0].node);return}if(N.key==="ArrowLeft"){if(N.preventDefault(),T.has(j.item.node.id)&&j.item.children.length)O(j.item.node.id,!1);else if(j.parentId){const V=i.find($=>$.id===j.parentId);V&&y(V)}return}N.preventDefault(),x(j.item.node.id)}}return b.length===0?g.jsx("p",{className:"empty",children:"No nodes loaded."}):g.jsx("div",{className:"preset-node-tree",role:"tree",tabIndex:0,onKeyDown:U,children:b.map(N=>g.jsx(dy,{item:N,assignedNodeId:a,engines:e,inheritedParams:{},selectedNodeId:s,usedNodeIds:l,expandedNodeIds:T,editingNodeId:v,openMenuNodeId:B,onCreateChild:c,onCreateGroup:f,onDelete:p,onEdit:x,onMenuToggle:A=>P(L=>L===A?"":A),onMove:m,onRename:h,onSelect:y,onSet:S,onToggle:O,onUnset:_},N.node.id))})}function dy({item:a,assignedNodeId:e,engines:i,inheritedParams:s,selectedNodeId:l,usedNodeIds:c,expandedNodeIds:f,editingNodeId:p,openMenuNodeId:m,onCreateChild:h,onCreateGroup:y,onDelete:S,onEdit:_,onMenuToggle:b,onMove:T,onRename:C,onSelect:v,onSet:x,onToggle:B,onUnset:P}){const D=f.has(a.node.id),O=m===a.node.id,U=a.node.id===l,N=a.node.id===e,A=c.has(a.node.id),L=ee.useMemo(()=>{function ge(K){return K.reduce((H,G)=>H+(c.has(G.node.id)?1:0)+ge(G.children),0)}return ge(a.children)},[a.children,c]),j=Kp(s,a.node.params),V=a.node.kind==="preset_root"?"root":a.node.kind==="chapter"?"group":a.node.kind,$=N?`${V} · assigned`:A?`${V} · used by slides`:L>0?`${V} · contains ${L} used preset${L===1?"":"s"}`:`${V} · unused`;async function pe(){b(a.node.id),window.confirm(`Delete preset "${a.node.name}"? This cannot be undone.`)&&await S(a.node)}return g.jsxs("div",{className:"tree-item",children:[g.jsxs("div",{className:`tree-node${U?" active":""}${N?" assigned":""}${A||L>0?" used":" unused"}`,children:[g.jsx("button",{"aria-label":a.children.length?`${D?"Collapse":"Expand"} ${a.node.name}`:`${a.node.name} has no children`,className:"tree-node-arrow",disabled:!a.children.length,type:"button",onClick:()=>B(a.node.id),children:a.children.length?D?"▾":"▸":"•"}),g.jsxs("button",{"aria-current":U?"true":void 0,className:"tree-node-main",role:"treeitem",type:"button",onClick:()=>v(a.node),children:[g.jsx("strong",{children:a.node.name}),g.jsx("small",{children:$})]}),g.jsxs("div",{className:"tree-node-action-shell",children:[g.jsx("button",{"aria-expanded":O,"aria-haspopup":"menu","aria-label":`Actions for ${a.node.name}`,className:"icon-button tree-node-edit node-action-trigger",title:"Preset actions",type:"button",onClick:ge=>{ge.stopPropagation(),b(a.node.id)},children:"⋯"}),O?g.jsxs("div",{className:"tree-node-action-menu",role:"menu",children:[g.jsx("button",{role:"menuitem",type:"button",onClick:()=>{b(a.node.id),_(a.node.id)},children:"Edit"}),g.jsx("button",{role:"menuitem",type:"button",onClick:()=>{b(a.node.id),h(a.node)},children:"Create child preset"}),g.jsx("button",{role:"menuitem",type:"button",onClick:()=>{b(a.node.id),y(a.node)},children:"Create child group"}),g.jsx("button",{disabled:a.siblingIndex===0,role:"menuitem",type:"button",onClick:()=>{b(a.node.id),T(a.node,-1)},children:"Move up"}),g.jsx("button",{disabled:a.siblingIndex>=a.siblingCount-1,role:"menuitem",type:"button",onClick:()=>{b(a.node.id),T(a.node,1)},children:"Move down"}),g.jsx("button",{className:"danger",role:"menuitem",type:"button",onClick:()=>{pe()},children:"Delete"})]}):null]})]}),p===a.node.id?g.jsx(TR,{engines:i,inheritedParams:s,node:a.node,resolvedParams:j,onClose:()=>_(""),onDelete:S,onRename:C,onSet:x,onUnset:P}):null,D&&a.children.length?g.jsx("div",{className:"tree-children",children:a.children.map(ge=>g.jsx(dy,{assignedNodeId:e,engines:i,inheritedParams:j,item:ge,usedNodeIds:c,expandedNodeIds:f,editingNodeId:p,openMenuNodeId:m,onCreateChild:h,onCreateGroup:y,onDelete:S,onEdit:_,onMenuToggle:b,onMove:T,onRename:C,onSelect:v,onSet:x,onToggle:B,onUnset:P,selectedNodeId:l},ge.node.id))}):null]})}function hy(a,e=[]){if(!ar(a))return[];const i=[];for(const[s,l]of Object.entries(a)){const c=[...e,s];c.join(".")==="simulation.initialCondition"||!ar(l)?i.push({path:c,value:l}):i.push(...hy(l,c))}return i}function yR(a){const e=a.join(".");return e!=="simulation.initialCondition"&&e!=="simulation.engineId"&&e!=="simulation.neighborhoodId"&&!e.startsWith("caClass.")}function SR(a){return a==="rendererId"?["renderer","id"]:a==="ruleId"?["simulation","ruleId"]:a.startsWith("grid.")?["simulation",...a.split(".")]:a.includes(".")?a.split("."):["simulation",a]}function MR(a){return a?Object.keys(a.params_schema):[]}function bR(a,e){const i=a.join(".");return MR(e).some(s=>SR(s).join(".")===i)}function ER(a){const e=a.trim();if(e==="")return"";try{return JSON.parse(e)}catch{return a}}function rx(a){return typeof a=="string"?a:JSON.stringify(a,null,2)}function TR({engines:a,inheritedParams:e,node:i,resolvedParams:s,onClose:l,onDelete:c,onRename:f,onSet:p,onUnset:m}){const[h,y]=ee.useState(i.name),S=Uh(s,["simulation","engineId"]),_=Ml(s),b=typeof S=="string"?a.find(P=>P.engine_kind===S):void 0,C=(b?Oa(b,_):!1)?b:void 0,v=hy(s).filter(P=>yR(P.path)&&!bR(P.path,C));ee.useEffect(()=>{y(i.name)},[i.name]);async function x(){const P=h.trim();if(!P){y(i.name);return}P!==i.name&&await f(i,P)}async function B(){!window.confirm(`Delete preset "${i.name}"? This cannot be undone.`)||await c(i)===!1||l()}return g.jsx("div",{className:"modal-backdrop",role:"presentation",onMouseDown:l,children:g.jsxs("section",{"aria-modal":"true",className:"property-modal",role:"dialog",onMouseDown:P=>P.stopPropagation(),children:[g.jsxs("header",{className:"property-modal-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Preset Editor"}),g.jsx("h2",{children:"Edit preset"})]}),g.jsx("button",{type:"button",onClick:l,children:"Close"})]}),g.jsxs("div",{className:"property-modal-list",children:[g.jsxs("section",{className:"preset-modal-stage preset-modal-identity",children:[g.jsxs("div",{className:"preset-modal-stage-heading",children:[g.jsx("span",{children:"i"}),g.jsxs("div",{children:[g.jsx("h3",{children:"Preset identity"}),g.jsx("p",{children:"Edit CA space, engine, and engine settings in the inspector."})]})]}),g.jsxs("label",{children:["Preset name",g.jsx("input",{autoFocus:!0,value:h,onChange:P=>y(P.target.value),onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),x())}})]}),g.jsx("button",{disabled:!h.trim()||h.trim()===i.name,type:"button",onClick:()=>{x()},children:"Save name"})]}),v.map(P=>{const D=Uh(i.params,P.path),O=Uh(e,P.path),U=D!==void 0&&!mR(D,O);return g.jsx(AR,{inheritedValue:O,isLocal:U,node:i,path:P.path,value:P.value,onSet:p,onUnset:m},P.path.join("."))}),v.length===0?g.jsx("p",{className:"empty",children:"No properties are resolved for this node."}):null,g.jsxs("footer",{className:"preset-modal-danger",children:[g.jsxs("div",{children:[g.jsx("strong",{children:"Delete preset"}),g.jsx("small",{children:"Slides referencing this preset must be reassigned first."})]}),g.jsx("button",{className:"danger",type:"button",onClick:()=>{B()},children:"Delete"})]})]})]})})}function AR({inheritedValue:a,isLocal:e,node:i,path:s,value:l,onSet:c,onUnset:f}){const[p,m]=ee.useState(rx(l));return ee.useEffect(()=>{m(rx(l))},[l]),g.jsxs("div",{className:"property-row",children:[g.jsxs("div",{className:"property-row-meta",children:[g.jsx("strong",{children:s.join(".")}),g.jsx("span",{className:e?"local":"inherited",children:e?"local override":"inherited"}),!e&&a!==void 0?g.jsxs("small",{children:["from parent: ",gR(s,a)]}):null]}),g.jsx("textarea",{value:p,onChange:h=>m(h.target.value)}),g.jsxs("div",{className:"property-row-actions",children:[g.jsx("button",{type:"button",onClick:()=>c(i,s,ER(p)),children:"Save"}),g.jsx("button",{className:"danger",disabled:!e,type:"button",onClick:()=>f(i,s),children:"🗑"})]})]})}function CR({activeSceneId:a,canDeleteSlide:e,sceneCount:i,scenes:s,onBack:l,onDeleteSlide:c,onEditScene:f,onReorderSlides:p,onSaveNewSlide:m,onSelectScene:h}){const[y,S]=ee.useState(""),[_,b]=ee.useState(null);function T(v){return(typeof v.scene.params.caption=="string"?v.scene.params.caption:"").split(/\r?\n/,1)[0].trim()||"No caption"}function C(v,x){if(!y||y===v)return;const B=s.find(N=>N.scene.id===y);if(!B)return;const P=s.filter(N=>N.scene.id!==y),D=P.findIndex(N=>N.scene.id===v);if(D===-1)return;const O=x==="after"?D+1:D,U=[...P];U.splice(O,0,B),p(U)}return g.jsxs("aside",{className:"panel slide-panel",children:[g.jsx("div",{className:"drawer-navigation",children:g.jsx("button",{type:"button",onClick:l,children:"Back"})}),g.jsxs("div",{className:"scene-list-header",children:[g.jsx("p",{className:"eyebrow",children:"Slides"}),g.jsx("span",{children:i})]}),s.length?s.map(v=>g.jsxs("div",{className:`scene-item${v.scene.id===a?" active":""}${v.scene.id===y?" dragging":""}${_?.sceneId===v.scene.id?` drop-${_.position}`:""}`,draggable:!0,onDragEnd:()=>{S(""),b(null)},onDragOver:x=>{x.preventDefault();const B=x.currentTarget.getBoundingClientRect(),P=x.clientY>B.top+B.height/2?"after":"before";b({sceneId:v.scene.id,position:P})},onDragStart:x=>{S(v.scene.id),x.dataTransfer.effectAllowed="move",x.dataTransfer.setData("text/plain",v.scene.id)},onDrop:x=>{x.preventDefault();const B=x.currentTarget.getBoundingClientRect(),P=x.clientY>B.top+B.height/2?"after":"before";C(v.scene.id,P),S(""),b(null)},children:[g.jsxs("button",{className:"scene-item-main",type:"button",onClick:()=>h(v),children:[g.jsx("span",{children:v.scene.order_index}),g.jsx("strong",{children:v.scene.title}),g.jsx("small",{className:"scene-caption-preview",children:T(v)})]}),g.jsx("button",{"aria-label":`Edit ${v.scene.title} metadata`,className:"scene-edit-button icon-button",type:"button",onClick:()=>f(v),children:"✎"})]},v.scene.id)):g.jsx("p",{className:"empty",children:"No slides yet. Choose a CA asset to create the first one."}),g.jsx("button",{className:"primary full-width",type:"button",onClick:m,children:"New slide"}),g.jsx("button",{className:"danger full-width",disabled:!e,type:"button",onClick:c,children:"Delete selected slide"})]})}const tr=24,ox="ca-studio-skin",Ap="ca-studio-gallery-tab",lx="ca-studio-engine-dimension",cx="ca-studio-icg-dimension",wR="windows-95",py=[{id:"retro-crt",label:"Retro CRT"},{id:"clean-lab",label:"Clean Lab"},{id:"blueprint",label:"Blueprint"},{id:"paper",label:"Paper Archive"},{id:"noir",label:"Noir Terminal"},{id:"windows-95",label:"Windows 95"}],RR=["decks","cas","engines","icgs"];function sr(){return Array.from({length:tr},()=>Array.from({length:tr},()=>!1))}function DR(){const a=sr(),e=10,i=10,s=[[1,0],[2,1],[0,2],[1,2],[2,2]];for(const[l,c]of s)a[i+c][e+l]=!0;return a}function no(a){return a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"untitled"}async function gt(a,e={}){const i=await fetch(a,{...e,headers:{"content-type":"application/json",...e.headers??{}}});if(!i.ok){const s=await i.text();throw new Error(NR(i,s))}return i.json()}function NR(a,e){const i=e.trim();if(!i)return`Request failed: ${a.status}`;const l=(/
(.*?)<\/pre>/is.exec(i)?.[1]??i).replace(/<[^>]*>/g," ").replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim();return l.startsWith("Cannot GET /api/ca/initial-condition-generators")?"Initial condition generator API is not available on this server. Restart the backend with the latest code.":l||`Request failed: ${a.status}`}function oo(a){const e=a?.params?.studio;return!e||typeof e!="object"||Array.isArray(e)?{}:e}function UR(a,e){const i={...oo(a)};for(const[s,l]of Object.entries(e))l===void 0?delete i[s]:i[s]=l;return{...a.params,studio:i}}function $p(a){const e=[];for(let i=0;i=0&&l>=0&&se+i.reduce((s,l)=>s+(l?1:0),0),0)}function gy(a){if(!(a instanceof HTMLElement))return!1;const e=a.tagName.toLowerCase();return a.isContentEditable||e==="input"||e==="select"||e==="textarea"}function _y(a){return RR.includes(a)}function LR(){const a=window.sessionStorage.getItem(Ap);return _y(a)?a:"decks"}function mo(a){return`/admin?tab=${a}`}function OR(a){return a?.startsWith("/admin/edit/")||a===mo("engines")?a:void 0}function ux(){const a=/^\/view\/decks\/([^/]+)/.exec(window.location.pathname);if(a)return{view:"viewer",deckId:a[1]};const e=/^\/admin\/edit\/([^/]+)/.exec(window.location.pathname);if(e){const f=new URLSearchParams(window.location.search);return{view:"edit",deckId:e[1],sceneId:f.get("scene")??void 0}}const i=/^\/admin\/libraries\/([^/]+)/.exec(window.location.pathname);if(i){const f=new URLSearchParams(window.location.search);return{view:"library",treeId:i[1],nodeId:f.get("node")??void 0,returnTo:OR(f.get("return"))}}if(/^\/admin\/icgs\/([^/]+)/.exec(window.location.pathname))return{view:"gallery",tab:"icgs"};const l=/^\/admin\/engines\/([^/]+)/.exec(window.location.pathname);if(l)return{view:"engine",engineId:l[1]};const c=new URLSearchParams(window.location.search).get("tab");return{view:"gallery",tab:_y(c)?c:LR()}}function Pi(a){window.history.pushState({},"",a),window.dispatchEvent(new PopStateEvent("popstate"))}function PR(){return{name:"Random soup",description:"Seed live cells randomly across the current voxel grid.",generatorKind:"random-soup",dimensions:2,states:2,density:.28,seed:"studio-seed"}}function vy(){return{name:"Conway Life",description:"Classic binary cellular automaton evolution rule.",engineKind:"game-of-life-2d",dimensions:2,states:2,ruleId:"B3/S23",rendererId:"2d-canvas",license:"internal",owner:"Glitch University",ipNotice:"Internal CA engine registry entry."}}function xy(a){return{density:{type:"range",label:"Density",default:a.density,min:0,max:1,step:.01},seed:{type:"string",label:"Seed",default:a.seed}}}function yy(a){return{density:a.density,seed:a.seed}}function Sy(a){return/^B[0-8]*\/S[0-8]*$/i.test(a)?a.toUpperCase():/^rule[-_\s]*\d{1,3}$/i.test(a)?a.replace(/^rule[-_\s]*/i,"Rule "):a==="wildfire-binary"?"Binary wildfire":a==="life-3d"?"3D Life":a==="generations-3d"?"3D Generations":a==="lattice-gas-3d"?"3D Lattice gas":a==="snake-3d"?"3D Snake":a}function IR(a){return a===1?[{value:"elementary-1d",label:"Elementary 1D"}]:a===3?[{value:"voxel-3d",label:"Voxel 3D"}]:[{value:"2d-canvas",label:"2D Canvas"},{value:"wildfire-2d",label:"Wildfire 2D"}]}function Qp(a){const e=IR(a.dimensions);return{ruleId:{type:"select",label:"Rule",default:a.ruleId,options:[{value:a.ruleId,label:Sy(a.ruleId)}]},rendererId:{type:"select",label:"Renderer",default:a.rendererId,options:e}}}function Jp(a){return{ruleId:a.ruleId,rendererId:a.rendererId}}function BR(a){const e=a.dimensions>=3?tr:1;return{caClass:{neighborhoodId:a.neighborhoodId,dimensions:a.dimensions,states:a.states},simulation:{engineId:a.dimensions===2&&a.states===2?"game-of-life-2d":"generic-voxel-ca",ruleId:a.ruleId,neighborhoodId:a.neighborhoodId,grid:{size:[tr,tr,e],boundary:"wrap",wrap:!0}},renderer:{id:a.rendererId},camera:{mode:a.dimensions===2?"2d":"3d"}}}function lo(a,e,i,s,l,c="wrap",f=!0){return{simulation:{...l?{engineId:l}:{},ruleId:a,neighborhoodId:e,grid:{boundary:c,wrap:c==="wrap"},...f?{initialCondition:{type:"cells",cells:$p(s)}}:{}},renderer:{id:i}}}function ws(a){return!!a&&typeof a=="object"&&!Array.isArray(a)}function FR(a,e){return JSON.stringify(a)===JSON.stringify(e)}function My(a,e){let i=a;for(const s of e){if(!ws(i)||!(s in i))return;i=i[s]}return i}function by(a){return a==="rendererId"?["renderer","id"]:a==="ruleId"?["simulation","ruleId"]:a.startsWith("grid.")?["simulation",...a.split(".")]:a.includes(".")?a.split("."):["simulation",a]}function fx(a,e){return typeof a=="number"&&Number.isFinite(a)?a:e}function dx(a){return typeof a=="number"&&Number.isFinite(a)?a:void 0}function zR(a,e){return typeof e.label=="string"?e.label:a}function Cp(a,e,i){const s=i.default_params[a];return s!==void 0?s:e.default}function ci(a,e){const i={...a};for(const[s,l]of Object.entries(e)){const c=i[s];i[s]=ws(c)&&ws(l)?ci(c,l):l}return i}function HR(a){return typeof a?.scene.params.caption=="string"?a.scene.params.caption:""}function GR(a){return a?.scene.params.autoplayOnSlideChange===!0}function hx(a,e){return ci(a,{simulation:{initialCondition:{type:"cells",cells:$p(e)}}})}function bu(a,e,i=[]){const s={};for(const[l,c]of Object.entries(a)){const f=[...i,l];if(ws(c)&&f.join(".")!=="simulation.initialCondition"){const p=bu(c,e,f);Object.keys(p).length>0&&(s[l]=p);continue}FR(c,My(e,f))||(s[l]=c)}return s}function eo(a,e){if(!e.parent_id)return{};const i=new Map(a.map(c=>[c.id,c])),s=[];let l=i.get(e.parent_id);for(;l;)s.unshift(l),l=l.parent_id?i.get(l.parent_id):void 0;return s.reduce((c,f)=>ci(c,f.params),{})}function VR(a,e){return a.sort_order-e.sort_order||a.name.localeCompare(e.name)||a.slug.localeCompare(e.slug)}function wp(a,e){return a.filter(i=>i.parent_id===e).sort(VR)}function px(a,e){const i=wp(a,e);return i.length===0?0:Math.max(...i.map(s=>s.sort_order))+1}function Ey(a,e){if(e.length===0)return a;const[i,...s]=e,l={...a};if(s.length===0)return delete l[i],l;const c=l[i];if(!ws(c))return l;const f=Ey(c,s);return Object.keys(f).length===0?delete l[i]:l[i]=f,l}function La(a,e,i){if(e.length===0)return a;const[s,...l]=e,c={...a};if(l.length===0)return c[s]=i,c;const f=c[s];return c[s]=La(ws(f)?f:{},l,i),c}function kR(){const[a,e]=ee.useState(ux),[i,s]=ee.useState(()=>{const c=window.localStorage.getItem(ox);return py.some(f=>f.id===c)?c:wR});ee.useEffect(()=>{const c=()=>e(ux());return window.addEventListener("popstate",c),()=>window.removeEventListener("popstate",c)},[]),ee.useEffect(()=>{document.documentElement.dataset.skin=i,window.localStorage.setItem(ox,i)},[i]);const l=a.view==="viewer"?g.jsx(t2,{deckId:a.deckId}):a.view==="edit"?g.jsx(n2,{deckId:a.deckId,initialSceneId:a.sceneId}):a.view==="library"?g.jsx(QR,{initialNodeId:a.nodeId,returnTo:a.returnTo,treeId:a.treeId}):a.view==="engine"?g.jsx($R,{engineId:a.engineId}):g.jsx(XR,{initialTab:a.tab});return a.view==="viewer"?l:g.jsxs("div",{className:"admin-app",children:[g.jsx("div",{className:"admin-app-content",children:l}),g.jsx(jR,{skin:i,onSkinChange:s})]})}function jR({skin:a,onSkinChange:e}){const[i,s]=ee.useState(()=>mx(new Date));return ee.useEffect(()=>{const l=window.setInterval(()=>s(mx(new Date)),3e4);return()=>window.clearInterval(l)},[]),g.jsxs("footer",{className:"app-footer",children:[g.jsx("div",{className:"footer-start","aria-hidden":"true",children:"Start"}),g.jsx("p",{children:"CA Lab is developed by Glitch University."}),g.jsxs("label",{className:"skin-picker",children:[g.jsx("span",{children:"Skin"}),g.jsx("select",{value:a,onChange:l=>e(l.target.value),children:py.map(l=>g.jsx("option",{value:l.id,children:l.label},l.id))})]}),g.jsx("div",{className:"footer-clock","aria-label":`Current time ${i}`,children:i})]})}function mx(a){return a.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function za(){return g.jsxs("span",{className:"win95-window-controls","aria-hidden":"true",children:[g.jsx("span",{children:"_"}),g.jsx("span",{children:"□"}),g.jsx("span",{children:"×"})]})}function XR({initialTab:a}){const[e,i]=ee.useState(a),[s,l]=ee.useState(()=>{const W=Number(window.sessionStorage.getItem(lx));return W===1||W===2||W===3?W:2}),[c,f]=ee.useState(()=>{const W=Number(window.sessionStorage.getItem(cx));return W===1||W===2||W===3?W:2}),[p,m]=ee.useState(!1),[h,y]=ee.useState([]),[S,_]=ee.useState([]),[b,T]=ee.useState([]),[C,v]=ee.useState(null),[x,B]=ee.useState(null),[P,D]=ee.useState(()=>new Set),[O,U]=ee.useState({}),[N,A]=ee.useState(()=>new Set),[L,j]=ee.useState([]),[V,$]=ee.useState("Game of Life: Glider Deck"),[pe,ge]=ee.useState("Game of Life Presets"),[K,H]=ee.useState(()=>PR()),[G,ne]=ee.useState(()=>vy()),[ye,xe]=ee.useState("Ready"),F=ee.useMemo(()=>({1:b.filter(W=>W.supported_classes.some(z=>z.dimensions===1)),2:b.filter(W=>W.supported_classes.some(z=>z.dimensions===2)),3:b.filter(W=>W.supported_classes.some(z=>z.dimensions===3))}),[b]),J=F[s],Ce=ee.useMemo(()=>({1:S.filter(W=>W.supported_classes.some(z=>z.dimensions===1)),2:S.filter(W=>W.supported_classes.some(z=>z.dimensions===2)),3:S.filter(W=>W.supported_classes.some(z=>z.dimensions===3))}),[S]),Ue=Ce[c],Ie=ee.useCallback(async()=>{y(await gt("/api/ca/decks"))},[]),ae=ee.useCallback(async()=>{_(await gt("/api/ca/initial-condition-generators"))},[]),Ae=ee.useCallback(async()=>{T(await gt("/api/ca/engines"))},[]),Ee=ee.useCallback(async()=>{j(await gt("/api/ca/preset-trees"))},[]);ee.useEffect(()=>{async function W(){try{await Promise.all([Ie(),Ee(),Ae()])}catch(z){xe(z instanceof Error?z.message:"Load failed");return}try{await ae()}catch(z){_([]),xe(z instanceof Error?z.message:"ICG list unavailable")}}W()},[Ie,Ae,ae,Ee]),ee.useEffect(()=>{i(a),window.sessionStorage.setItem(Ap,a)},[a]);function He(W){i(W),m(!1),window.sessionStorage.setItem(Ap,W),window.history.replaceState({},"",mo(W))}function nt(W){l(W),window.sessionStorage.setItem(lx,String(W))}function Ke(){const W=s===1?"elementary-1d":s===3?"voxel-3d":"2d-canvas";ne(z=>({...z,dimensions:s,rendererId:W})),m(!0)}async function zt(W){if(P.has(W.id)){D(z=>{const Ye=new Set(z);return Ye.delete(W.id),Ye});return}if(D(z=>new Set(z).add(W.id)),!O[W.id]){A(z=>new Set(z).add(W.id));try{const z=await gt(`/api/ca/engines/${W.id}/usage`);U(Ye=>({...Ye,[W.id]:z}))}catch(z){xe(z instanceof Error?z.message:"Engine usage could not be loaded"),D(Ye=>{const xt=new Set(Ye);return xt.delete(W.id),xt})}finally{A(z=>{const Ye=new Set(z);return Ye.delete(W.id),Ye})}}}function ht(W){const z=new URLSearchParams({node:W.node_id,return:mo("engines")});Pi(`/admin/libraries/${W.tree_id}?${z.toString()}`)}function Et(W){f(W),window.sessionStorage.setItem(cx,String(W))}function yt(){H(W=>({...W,dimensions:c})),m(!0)}async function St(){try{xe("Creating deck...");const W=Date.now(),z=await gt("/api/ca/decks",{method:"POST",body:JSON.stringify({slug:`${no(V)}-${W}`,title:V.trim()||"Untitled deck",params:{studio:{}}})});m(!1),Pi(`/admin/edit/${z.id}`)}catch(W){xe(W instanceof Error?W.message:"Deck create failed")}}async function Mt(){try{xe(`Creating node tree "${pe}"...`);const W=Date.now(),z=await gt("/api/ca/preset-trees",{method:"POST",body:JSON.stringify({slug:`${no(pe)}-${W}`,name:pe.trim()||"Untitled node tree",description:"Admin-authored CA preset tree"})});j(Ye=>[z,...Ye]),m(!1),xe(`Created node tree "${z.name}"`)}catch(W){xe(W instanceof Error?W.message:"Node tree create failed")}}async function Ht(W){const z=`${W.node_count} ${W.node_count===1?"node":"nodes"}`;if(window.confirm(`Delete "${W.name}" and its ${z}? This cannot be undone.`))try{xe(`Deleting CA library "${W.name}"...`);const Ye=await fetch(`/api/ca/preset-trees/${W.id}`,{method:"DELETE"});if(!Ye.ok){const xt=await Ye.json().catch(()=>null);throw new Error(xt?.error?`Could not delete "${W.name}": ${xt.error}`:`Could not delete "${W.name}". It may still be referenced by a slide.`)}j(xt=>xt.filter(I=>I.id!==W.id)),xe(`Deleted CA library "${W.name}"`)}catch(Ye){xe(Ye instanceof Error?Ye.message:"CA library delete failed")}}async function Gt(W){try{const Ye=oo(W).presetTreeId,xt=Ye?h.filter(me=>me.id!==W.id&&oo(me).presetTreeId===Ye):[],I=!!(Ye&&xt.length===0),E=I?`Delete "${W.title}"? It is the only deck using its preset tree, so the tree can be removed as well.`:`Delete "${W.title}"?`;if(!window.confirm(E))return;if(xe(`Deleting "${W.title}"...`),!(await fetch(`/api/ca/decks/${W.id}`,{method:"DELETE"})).ok)throw new Error("Unable to delete deck");y(me=>me.filter(Ne=>Ne.id!==W.id));let se="";if(I&&Ye&&window.confirm("Remove the now-unused preset tree too?"))try{(await fetch(`/api/ca/preset-trees/${Ye}`,{method:"DELETE"})).ok||(se="Deck deleted, but the preset tree could not be removed.")}catch{se="Deck deleted, but the preset tree could not be removed."}await Ie(),xe(se||`Deleted "${W.title}"`)}catch(z){xe(z instanceof Error?z.message:"Deck delete failed")}}async function st(){try{xe(`Creating ICG "${K.name}"...`);const W=Date.now(),z=await gt("/api/ca/initial-condition-generators",{method:"POST",body:JSON.stringify({slug:`${no(K.name)}-${W}`,name:K.name,description:K.description.trim()||null,generatorKind:K.generatorKind,supportedClasses:[{dimensions:K.dimensions,states:K.states}],paramsSchema:xy(K),defaultParams:yy(K)})});_(Ye=>[z,...Ye]),m(!1),xe(`Created ICG "${z.name}"`)}catch(W){xe(W instanceof Error?W.message:"ICG create failed")}}async function It(){try{xe(`Creating engine "${G.name}"...`);const W=Date.now(),z=await gt("/api/ca/engines",{method:"POST",body:JSON.stringify({slug:`${no(G.name)}-${W}`,name:G.name.trim()||"Untitled CA engine",description:G.description.trim()||null,engineKind:G.engineKind,license:G.license.trim()||null,owner:G.owner.trim()||null,ipNotice:G.ipNotice.trim()||null,supportedClasses:[{dimensions:G.dimensions,states:G.states}],paramsSchema:Qp(G),defaultParams:Jp(G)})});T(Ye=>[z,...Ye]),m(!1),xe(`Created engine "${z.name}"`)}catch(W){xe(W instanceof Error?W.message:"Engine create failed")}}return g.jsxs("main",{className:"shell",children:[g.jsxs("header",{className:"gallery-hero panel",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"CA Studio Admin"}),g.jsx("h1",{children:"CA Studio"}),g.jsx("p",{children:"Explore the wonderful and strange world of cellular automata."})]}),g.jsx("div",{className:"status",children:ye}),g.jsx(za,{})]}),g.jsxs("nav",{"aria-label":"Gallery sections",className:"gallery-tabs",children:[g.jsx("button",{className:e==="decks"?"active":"",type:"button",onClick:()=>He("decks"),children:"Decks"}),g.jsx("button",{className:e==="cas"?"active":"",type:"button",onClick:()=>He("cas"),children:"CAs"}),g.jsx("button",{className:e==="engines"?"active":"",type:"button",onClick:()=>He("engines"),children:"CA Engines"}),g.jsx("button",{className:e==="icgs"?"active":"",type:"button",onClick:()=>He("icgs"),children:"ICGs"})]}),g.jsxs("section",{className:"panel gallery-tab-panel",children:[e==="decks"?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"gallery-section-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Decks"}),g.jsx("h2",{children:"Presentations"})]}),g.jsxs("div",{className:"gallery-section-actions",children:[g.jsx("span",{children:h.length}),g.jsx("button",{className:"primary",type:"button",onClick:()=>m(!0),children:"New deck"})]})]}),g.jsx("p",{className:"gallery-tab-description",children:"A deck is a narrated sequence of slides. Slides can reference CA presets from a library, then add caption, playback, and recording context."}),g.jsxs("div",{className:"gallery-list",children:[h.map(W=>g.jsxs("article",{"aria-label":`Open ${W.title}`,className:"deck-card gallery-entity-card deck-entity-card panel",role:"link",tabIndex:0,onClick:()=>Pi(`/admin/edit/${W.id}`),onKeyDown:z=>{z.target===z.currentTarget&&(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),Pi(`/admin/edit/${W.id}`))},children:[g.jsx("span",{className:"gallery-card-icon","aria-hidden":"true"}),g.jsx("span",{children:W.slug}),g.jsx("strong",{children:W.title}),g.jsx("small",{children:oo(W).presetTreeId?"tree selected":"choose a node tree in editor"}),g.jsxs("div",{className:"gallery-card-controls",children:[g.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),Pi(`/view/decks/${W.id}`)},children:"View"}),g.jsx("button",{"aria-label":`Delete ${W.title}`,className:"danger deck-trash-button",type:"button",onClick:z=>{z.stopPropagation(),Gt(W)},children:"🗑"})]})]},W.id)),h.length===0?g.jsx("p",{className:"empty",children:"No decks yet."}):null]})]}):null,e==="cas"?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"gallery-section-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"CAs"}),g.jsx("h2",{children:"Preset libraries"})]}),g.jsxs("div",{className:"gallery-section-actions",children:[g.jsx("span",{children:L.length}),g.jsx("button",{className:"primary",type:"button",onClick:()=>m(!0),children:"New CA"})]})]}),g.jsx("p",{className:"gallery-tab-description",children:"A CA preset library is a tree of reusable simulation states. Child presets inherit renderer, rule, neighbourhood, camera, and initial-condition settings from their parents."}),g.jsxs("div",{className:"gallery-list",children:[L.map(W=>g.jsxs("article",{"aria-label":`Open ${W.name}`,className:`deck-card gallery-entity-card library-card panel${W.node_count===0?" empty-library":""}`,role:"link",tabIndex:0,onClick:()=>Pi(`/admin/libraries/${W.id}`),onKeyDown:z=>{z.target===z.currentTarget&&(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),Pi(`/admin/libraries/${W.id}`))},children:[g.jsx("span",{className:"gallery-card-icon","aria-hidden":"true"}),g.jsx("span",{children:W.slug}),g.jsx("strong",{children:W.name}),g.jsx("small",{children:W.node_count===0?"Empty library":`${W.node_count} ${W.node_count===1?"node":"nodes"}`}),g.jsx("div",{className:"gallery-card-controls gallery-card-controls-end",children:g.jsx("button",{"aria-label":`Delete ${W.name}`,className:"danger deck-trash-button",title:`Delete ${W.name}`,type:"button",onClick:z=>{z.stopPropagation(),Ht(W)},children:"🗑"})})]},W.id)),L.length===0?g.jsx("p",{className:"empty",children:"No CA libraries yet."}):null]})]}):null,e==="engines"?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"gallery-section-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"CA Engines"}),g.jsx("h2",{children:"Evolution functions"})]}),g.jsxs("div",{className:"gallery-section-actions",children:[g.jsx("span",{children:J.length}),g.jsx("button",{className:"primary",type:"button",onClick:Ke,children:"New engine"})]})]}),g.jsx("p",{className:"gallery-tab-description",children:"A CA engine is an evolution function. Presets select compatible engines by dimensions and state count; licence and ownership metadata travel with the registry entry."}),g.jsx("nav",{"aria-label":"Engine dimensions",className:"dimension-tabs",children:[1,2,3].map(W=>g.jsxs("button",{"aria-selected":s===W,className:s===W?"active":"",role:"tab",type:"button",onClick:()=>nt(W),children:[W,"D",g.jsx("span",{children:F[W].length})]},W))}),g.jsxs("div",{className:"gallery-list",children:[J.map(W=>g.jsxs("article",{className:"deck-card engine-gallery-card engine-entity-card panel",children:[g.jsxs("button",{"aria-label":`Edit ${W.name}`,className:"engine-card-main",type:"button",onClick:()=>B(W),children:[g.jsx("span",{className:"gallery-card-icon","aria-hidden":"true"}),g.jsx("span",{children:W.engine_kind}),g.jsx("strong",{children:W.name}),g.jsx("small",{children:gx(W.supported_classes)}),W.license?g.jsxs("small",{children:["License: ",W.license]}):null,W.owner?g.jsxs("small",{children:["Owner: ",W.owner]}):null]}),g.jsxs("button",{"aria-expanded":P.has(W.id),className:"engine-usage-toggle",type:"button",onClick:()=>{zt(W)},children:[g.jsx("span",{children:P.has(W.id)?"▾":"▸"}),"Preset usage",O[W.id]?g.jsx("small",{children:O[W.id].length}):null]}),P.has(W.id)?g.jsxs("div",{className:"engine-usage-list",children:[N.has(W.id)?g.jsx("p",{className:"empty",children:"Loading presets..."}):null,!N.has(W.id)&&(O[W.id]?.length??0)===0?g.jsx("p",{className:"empty",children:"No presets currently use this engine."}):null,O[W.id]?.map(z=>g.jsxs("button",{type:"button",onClick:()=>ht(z),children:[g.jsx("span",{children:z.tree_name}),g.jsx("strong",{children:z.node_name}),g.jsx("small",{children:z.node_kind==="preset_root"?"root":z.node_kind})]},`${z.tree_id}:${z.node_id}`))]}):null]},W.id)),J.length===0?g.jsxs("p",{className:"empty",children:["No ",s,"D CA engines yet."]}):null]})]}):null,e==="icgs"?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"gallery-section-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"ICGs"}),g.jsx("h2",{children:"Initial condition generators"})]}),g.jsxs("div",{className:"gallery-section-actions",children:[g.jsx("span",{children:Ue.length}),g.jsx("button",{className:"primary",type:"button",onClick:yt,children:"New ICG"})]})]}),g.jsx("p",{className:"gallery-tab-description",children:"An ICG is a deterministic tool that creates initial cell states for compatible CA classes. Running one writes concrete cells into a preset."}),g.jsx("nav",{"aria-label":"ICG dimensions",className:"dimension-tabs",children:[1,2,3].map(W=>g.jsxs("button",{"aria-selected":c===W,className:c===W?"active":"",role:"tab",type:"button",onClick:()=>Et(W),children:[W,"D",g.jsx("span",{children:Ce[W].length})]},W))}),g.jsxs("div",{className:"gallery-list",children:[Ue.map(W=>g.jsxs("article",{"aria-label":`Edit ${W.name}`,className:"deck-card gallery-entity-card icg-entity-card panel",role:"button",tabIndex:0,onClick:()=>v(W),onKeyDown:z=>{z.target===z.currentTarget&&(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),v(W))},children:[g.jsx("span",{className:"gallery-card-icon","aria-hidden":"true"}),g.jsx("span",{children:W.generator_kind}),g.jsx("strong",{children:W.name}),g.jsx("small",{children:gx(W.supported_classes)}),W.description?g.jsx("small",{children:W.description}):null]},W.id)),Ue.length===0?g.jsxs("p",{className:"empty",children:["No ",c,"D generators yet."]}):null]})]}):null]}),g.jsxs("div",{className:"win95-statusbar","aria-hidden":"true",children:[g.jsxs("span",{children:["Objects: ",e==="decks"?h.length:e==="cas"?L.length:e==="engines"?J.length:Ue.length]}),g.jsxs("span",{children:["Status: ",ye]}),g.jsx("span",{children:"CA Lab Studio"})]}),p?g.jsx(WR,{activeTab:e,deckName:V,engineConfig:G,icgConfig:K,treeName:pe,onClose:()=>m(!1),onCreateDeck:()=>{St()},onCreateEngine:()=>{It()},onCreateIcg:()=>{st()},onCreateTree:()=>{Mt()},onDeckNameChange:$,onEngineConfigChange:ne,onIcgConfigChange:H,onTreeNameChange:ge}):null,x?g.jsx(qR,{engine:x,onClose:()=>B(null),onSaved:W=>{T(z=>z.map(Ye=>Ye.id===W.id?W:Ye)),B(null),xe(`Saved engine "${W.name}"`)}}):null,C?g.jsx(KR,{generator:C,onClose:()=>v(null),onSaved:W=>{_(z=>z.map(Ye=>Ye.id===W.id?W:Ye)),v(null),xe(`Saved ICG "${W.name}"`)}}):null]})}function WR({activeTab:a,deckName:e,engineConfig:i,icgConfig:s,treeName:l,onClose:c,onCreateDeck:f,onCreateEngine:p,onCreateIcg:m,onCreateTree:h,onDeckNameChange:y,onEngineConfigChange:S,onIcgConfigChange:_,onTreeNameChange:b}){const T={decks:"deck",cas:"CA library",engines:"CA engine",icgs:"initial condition generator"},C={decks:f,cas:h,engines:p,icgs:m}[a];return ee.useEffect(()=>{function v(x){x.key==="Escape"&&c()}return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[c]),g.jsx("div",{className:"modal-backdrop",role:"presentation",onMouseDown:c,children:g.jsxs("section",{"aria-modal":"true",className:"property-modal gallery-create-modal",role:"dialog",onMouseDown:v=>v.stopPropagation(),children:[g.jsxs("header",{className:"property-modal-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Create"}),g.jsxs("h2",{children:["New ",T[a]]})]}),g.jsxs("div",{className:"window-action-cluster",children:[g.jsx(za,{}),g.jsx("button",{type:"button",onClick:c,children:"Close"})]})]}),g.jsxs("div",{className:"gallery-create-body",children:[a==="decks"?g.jsxs("label",{children:["Deck name",g.jsx("input",{autoFocus:!0,value:e,onChange:v=>y(v.target.value)})]}):null,a==="cas"?g.jsxs("label",{children:["Library name",g.jsx("input",{autoFocus:!0,value:l,onChange:v=>b(v.target.value)})]}):null,a==="engines"?g.jsx(em,{config:i,onChange:S}):null,a==="icgs"?g.jsx(Ty,{config:s,onChange:_}):null,g.jsxs("div",{className:"gallery-create-actions",children:[g.jsx("button",{type:"button",onClick:c,children:"Cancel"}),g.jsxs("button",{className:"primary",type:"button",onClick:C,children:["Create ",T[a]]})]})]})]})})}function gx(a){return a.map(e=>`${e.dimensions}D · ${e.states} states`).join(", ")}function Ty({config:a,onChange:e}){return g.jsxs("div",{className:"root-config-fields",children:[g.jsx("p",{className:"eyebrow",children:"Initial Condition Generator"}),g.jsxs("label",{children:["Generator name",g.jsx("input",{value:a.name,onChange:i=>e(s=>({...s,name:i.target.value}))})]}),g.jsxs("label",{children:["Description",g.jsx("textarea",{value:a.description,onChange:i=>e(s=>({...s,description:i.target.value}))})]}),g.jsxs("div",{className:"root-config-grid",children:[g.jsxs("label",{children:["Dimensions",g.jsxs("select",{value:a.dimensions,onChange:i=>e(s=>({...s,dimensions:Number(i.target.value)})),children:[g.jsx("option",{value:1,children:"1D"}),g.jsx("option",{value:2,children:"2D"}),g.jsx("option",{value:3,children:"3D"})]})]}),g.jsxs("label",{children:["States",g.jsx("input",{min:2,step:1,type:"number",value:a.states,onChange:i=>e(s=>({...s,states:Math.max(2,Number(i.target.value)||2)}))})]}),g.jsxs("label",{children:["Density",g.jsx("input",{max:1,min:0,step:.01,type:"number",value:a.density,onChange:i=>e(s=>({...s,density:Math.max(0,Math.min(1,Number(i.target.value)||0))}))})]})]}),g.jsxs("label",{children:["Seed",g.jsx("input",{value:a.seed,onChange:i=>e(s=>({...s,seed:i.target.value}))})]})]})}function em({config:a,onChange:e}){return g.jsxs("div",{className:"root-config-fields",children:[g.jsx("p",{className:"eyebrow",children:"CA Engine"}),g.jsxs("label",{children:["Engine name",g.jsx("input",{value:a.name,onChange:i=>e(s=>({...s,name:i.target.value}))})]}),g.jsxs("label",{children:["Description",g.jsx("textarea",{value:a.description,onChange:i=>e(s=>({...s,description:i.target.value}))})]}),g.jsxs("div",{className:"root-config-grid",children:[g.jsxs("label",{children:["Engine kind",g.jsx("input",{value:a.engineKind,onChange:i=>e(s=>({...s,engineKind:i.target.value}))})]}),g.jsxs("label",{children:["Rule id",g.jsx("input",{value:a.ruleId,onChange:i=>e(s=>({...s,ruleId:i.target.value}))})]}),g.jsxs("label",{children:["Renderer",g.jsxs("select",{value:a.rendererId,onChange:i=>e(s=>({...s,rendererId:i.target.value})),children:[g.jsx("option",{value:"2d-canvas",children:"2D Canvas"}),g.jsx("option",{value:"elementary-1d",children:"Elementary 1D"}),g.jsx("option",{value:"wildfire-2d",children:"Wildfire 2D"}),g.jsx("option",{value:"voxel-3d",children:"Voxel 3D"})]})]}),g.jsxs("label",{children:["Dimensions",g.jsxs("select",{value:a.dimensions,onChange:i=>e(s=>({...s,dimensions:Number(i.target.value)})),children:[g.jsx("option",{value:1,children:"1D"}),g.jsx("option",{value:2,children:"2D"}),g.jsx("option",{value:3,children:"3D"})]})]}),g.jsxs("label",{children:["States",g.jsx("input",{min:2,step:1,type:"number",value:a.states,onChange:i=>e(s=>({...s,states:Math.max(2,Number(i.target.value)||2)}))})]}),g.jsxs("label",{children:["License",g.jsx("input",{value:a.license,onChange:i=>e(s=>({...s,license:i.target.value}))})]}),g.jsxs("label",{children:["Owner",g.jsx("input",{value:a.owner,onChange:i=>e(s=>({...s,owner:i.target.value}))})]})]}),g.jsxs("label",{children:["IP notice",g.jsx("textarea",{value:a.ipNotice,onChange:i=>e(s=>({...s,ipNotice:i.target.value}))})]})]})}function qR({engine:a,onClose:e,onSaved:i}){const[s,l]=ee.useState(()=>Rp(a)),[c,f]=ee.useState(!1),[p,m]=ee.useState("");ee.useEffect(()=>{function y(S){S.key==="Escape"&&!c&&e()}return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[e,c]);async function h(){try{f(!0),m("");const y=await gt(`/api/ca/engines/${a.id}`,{method:"PATCH",body:JSON.stringify({name:s.name.trim()||"Untitled CA engine",description:s.description.trim()||null,engineKind:s.engineKind,license:s.license.trim()||null,owner:s.owner.trim()||null,ipNotice:s.ipNotice.trim()||null,supportedClasses:[{dimensions:s.dimensions,states:s.states}],paramsSchema:Qp(s),defaultParams:Jp(s)})});i(y)}catch(y){m(y instanceof Error?y.message:"Engine save failed")}finally{f(!1)}}return g.jsx("div",{className:"modal-backdrop",role:"presentation",onMouseDown:()=>{c||e()},children:g.jsxs("section",{"aria-modal":"true",className:"property-modal gallery-create-modal",role:"dialog",onMouseDown:y=>y.stopPropagation(),children:[g.jsxs("header",{className:"property-modal-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"CA Engine"}),g.jsxs("h2",{children:["Edit ",a.name]})]}),g.jsxs("div",{className:"window-action-cluster",children:[g.jsx(za,{}),g.jsx("button",{disabled:c,type:"button",onClick:e,children:"Close"})]})]}),g.jsxs("div",{className:"gallery-create-body",children:[g.jsx(em,{config:s,onChange:l}),p?g.jsx("p",{className:"compatibility-warning",role:"alert",children:p}):null,g.jsxs("div",{className:"gallery-create-actions",children:[g.jsx("button",{disabled:c,type:"button",onClick:e,children:"Cancel"}),g.jsx("button",{className:"primary",disabled:c,type:"button",onClick:()=>{h()},children:c?"Saving...":"Save engine"})]})]})]})})}function _x(a){const e=a.supported_classes[0];return{name:a.name,description:a.description??"",generatorKind:a.generator_kind,dimensions:e?.dimensions??2,states:typeof e?.states=="number"?e.states:2,density:typeof a.default_params.density=="number"?a.default_params.density:.28,seed:typeof a.default_params.seed=="string"?a.default_params.seed:"studio-seed"}}function Rp(a){const e=a.supported_classes[0];return{name:a.name,description:a.description??"",engineKind:a.engine_kind,dimensions:e?.dimensions??2,states:typeof e?.states=="number"?e.states:2,ruleId:typeof a.default_params.ruleId=="string"?a.default_params.ruleId:"B3/S23",rendererId:typeof a.default_params.rendererId=="string"?a.default_params.rendererId:"2d-canvas",license:a.license??"",owner:a.owner??"",ipNotice:a.ip_notice??""}}function YR({disabled:a,engine:e,settings:i,onSet:s}){const l=e?Object.entries(e.params_schema).filter(c=>ws(c[1])):[];return e?l.length===0?g.jsx("p",{className:"param-empty",children:"This engine does not expose editable settings."}):g.jsx("div",{className:"engine-settings-grid inspector-engine-settings",children:l.map(([c,f])=>{const p=by(c),m=My(i,p)??Cp(c,f,e);return g.jsx(ZR,{disabled:a,engine:e,paramKey:c,path:p,schema:f,value:m,onSet:s},c)})}):g.jsx("p",{className:"param-empty",children:"Select a compatible engine to edit engine settings."})}function ZR({disabled:a,engine:e,paramKey:i,path:s,schema:l,value:c,onSet:f}){const p=typeof l.type=="string"?l.type:"string",m=zR(i,l);if(p==="boolean")return g.jsxs("label",{className:"engine-setting-toggle",children:[g.jsx("input",{checked:c===!0,disabled:a,type:"checkbox",onChange:h=>f(s,h.target.checked)}),g.jsx("span",{children:m})]});if(p==="select"&&Array.isArray(l.options)){const h=l.options.filter(ws),y=new Set(h.map(T=>String(T.value))),S=String(c??""),_=String(Cp(i,l,e)??""),b=S&&!y.has(S)?S:"";return g.jsxs("label",{children:[m,g.jsxs("select",{disabled:a,value:b||S,onChange:T=>f(s,T.target.value),children:[b?g.jsxs("option",{disabled:!0,value:b,children:["Unsupported: ",b]}):null,h.map(T=>{const C=T.value;return g.jsx("option",{value:String(C),children:typeof T.label=="string"?T.label:String(C)},String(C))})]}),b?g.jsxs("small",{className:"engine-setting-warning",children:["Not supported by this engine.",g.jsxs("button",{disabled:a||!_,type:"button",onClick:()=>f(s,_),children:["Use ",Sy(_)]})]}):null]})}return p==="number"||p==="range"?g.jsxs("label",{children:[m,g.jsx("input",{disabled:a,max:dx(l.max),min:dx(l.min),step:fx(l.step,p==="range"?.01:1),type:p==="range"?"range":"number",value:typeof c=="number"?c:fx(Cp(i,l,e),0),onChange:h=>f(s,Number(h.target.value))})]}):g.jsxs("label",{children:[m,g.jsx("input",{disabled:a,type:p==="color"?"color":"text",value:typeof c=="string"||typeof c=="number"?String(c):"",onChange:h=>f(s,h.target.value)})]})}function KR({generator:a,onClose:e,onSaved:i}){const[s,l]=ee.useState(()=>_x(a)),[c,f]=ee.useState(!1),[p,m]=ee.useState("");ee.useEffect(()=>{l(_x(a)),m("")},[a]);async function h(){f(!0),m("");try{const y=await gt(`/api/ca/initial-condition-generators/${a.id}`,{method:"PATCH",body:JSON.stringify({name:s.name.trim()||"Untitled ICG",description:s.description.trim()||null,generatorKind:s.generatorKind,supportedClasses:[{dimensions:s.dimensions,states:s.states}],paramsSchema:xy(s),defaultParams:yy(s)})});i(y)}catch(y){m(y instanceof Error?y.message:"ICG save failed")}finally{f(!1)}}return g.jsx("div",{className:"modal-backdrop",role:"presentation",onMouseDown:()=>{c||e()},children:g.jsxs("section",{"aria-modal":"true",className:"property-modal gallery-create-modal",role:"dialog",onMouseDown:y=>y.stopPropagation(),children:[g.jsxs("header",{className:"property-modal-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Initial Condition Generator"}),g.jsxs("h2",{children:["Edit ",a.name]})]}),g.jsxs("div",{className:"window-action-cluster",children:[g.jsx(za,{}),g.jsx("button",{disabled:c,type:"button",onClick:e,children:"Close"})]})]}),g.jsxs("div",{className:"gallery-create-body",children:[g.jsx(Ty,{config:s,onChange:l}),p?g.jsx("p",{className:"compatibility-warning",role:"alert",children:p}):null,g.jsxs("div",{className:"gallery-create-actions",children:[g.jsx("button",{disabled:c,type:"button",onClick:e,children:"Cancel"}),g.jsx("button",{className:"primary",disabled:c,type:"button",onClick:()=>{h()},children:c?"Saving...":"Save ICG"})]})]})]})})}function $R({engineId:a}){const[e,i]=ee.useState(null),[s,l]=ee.useState(()=>vy()),[c,f]=ee.useState("Loading engine...");ee.useEffect(()=>{async function m(){try{const h=await gt(`/api/ca/engines/${a}`);i(h),l(Rp(h)),f("Engine ready")}catch(h){f(h instanceof Error?h.message:"Engine load failed")}}m()},[a]);async function p(){if(e)try{f(`Saving "${s.name}"...`);const m=await gt(`/api/ca/engines/${e.id}`,{method:"PATCH",body:JSON.stringify({name:s.name.trim()||"Untitled CA engine",description:s.description.trim()||null,engineKind:s.engineKind,license:s.license.trim()||null,owner:s.owner.trim()||null,ipNotice:s.ipNotice.trim()||null,supportedClasses:[{dimensions:s.dimensions,states:s.states}],paramsSchema:Qp(s),defaultParams:Jp(s)})});i(m),l(Rp(m)),f(`Saved "${m.name}"`)}catch(m){f(m instanceof Error?m.message:"Engine save failed")}}return g.jsxs("main",{className:"shell",children:[g.jsxs("header",{className:"topbar",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"CA Engine Editor"}),g.jsx("h1",{children:e?.name??"Evolution function"})]}),g.jsxs("div",{className:"topbar-actions",children:[g.jsx("button",{type:"button",onClick:()=>Pi(mo("engines")),children:"Gallery"}),g.jsx("div",{className:"status",children:c})]})]}),g.jsxs("section",{className:"panel icg-editor-panel",children:[g.jsx(em,{config:s,onChange:l}),g.jsx("button",{className:"primary",disabled:!e,type:"button",onClick:()=>{p()},children:"Save engine"})]})]})}function QR({initialNodeId:a,returnTo:e,treeId:i}){const[s,l]=ee.useState(null),[c,f]=ee.useState([]),[p,m]=ee.useState([]),[h,y]=ee.useState([]),[S,_]=ee.useState([]),[b,T]=ee.useState(""),[C,v]=ee.useState(""),[x,B]=ee.useState(""),[P,D]=ee.useState(.28),[O,U]=ee.useState("studio-seed"),[N,A]=ee.useState("Untitled preset"),[L,j]=ee.useState(""),[V,$]=ee.useState(2),[pe,ge]=ee.useState(2),[K,H]=ee.useState("2d-canvas"),[G,ne]=ee.useState("moore"),[ye,xe]=ee.useState("B3/S23"),[F,J]=ee.useState(""),[Ce,Ue]=ee.useState("wrap"),[Ie,ae]=ee.useState(()=>sr()),[Ae,Ee]=ee.useState(0),[He,nt]=ee.useState(!1),[Ke,zt]=ee.useState(!1),[ht,Et]=ee.useState(!1),[yt,St]=ee.useState(()=>!window.matchMedia("(max-width: 820px)").matches),[Mt,Ht]=ee.useState(()=>!window.matchMedia("(max-width: 820px)").matches),[Gt,st]=ee.useState("ca"),[It,W]=ee.useState("Loading library..."),[z,Ye]=ee.useState(""),[xt,I]=ee.useState(0),E=ee.useRef(!1),X=c.find(re=>re.id===b)??null,se=ee.useMemo(()=>new Set(p.map(re=>re.node_id)),[p]),me=ee.useMemo(()=>({dimensions:V,states:pe,neighborhoodId:G}),[V,G,pe]),Ne=X?ci(ci(eo(c,X),X.params),ci(lo(ye,G,K,Ie,F,Ce),{caClass:me})):ci(lo(ye,G,K,Ie,F,Ce),{caClass:me}),Oe=Ml(Ne),_e=ee.useMemo(()=>h.filter(re=>Oa(re,Oe)),[h,Oe]),he=ee.useMemo(()=>S.filter(re=>Oa(re,Oe)),[S,Oe]),Le=ee.useMemo(()=>he.find(re=>re.id===x)??he.find(re=>re.engine_kind===F),[he,F,x]),je=ee.useMemo(()=>Nh(Oe),[Oe]),ze=ee.useCallback(async()=>{const[re,we]=await Promise.all([gt(`/api/ca/preset-trees/${i}/nodes`),gt(`/api/ca/preset-trees/${i}/node-usage`)]);return f(re),m(we),re},[i]),Fe=ee.useCallback(async()=>{const[re,we,Ge,it]=await Promise.all([gt("/api/ca/preset-trees"),gt(`/api/ca/preset-trees/${i}/nodes`),gt(`/api/ca/preset-trees/${i}/node-usage`),gt("/api/ca/engines")]);l(re.find(vt=>vt.id===i)??null),f(we),m(Ge),_(it);try{y(await gt("/api/ca/initial-condition-generators"))}catch{y([])}const lt=we.find(vt=>vt.id===a)??we[0];lt?await Je(lt.id):W("Library ready. Add the first top-level preset.")},[a,i]);ee.useEffect(()=>{Fe().catch(re=>W(re instanceof Error?re.message:"Library load failed"))},[Fe]),ee.useEffect(()=>{async function re(){try{const[we,Ge]=await Promise.all([gt("/api/ca/initial-condition-generators"),gt("/api/ca/engines")]);y(we),_(Ge)}catch{y([]),_([])}}return window.addEventListener("focus",re),()=>window.removeEventListener("focus",re)},[]),ee.useEffect(()=>{C&&!_e.some(re=>re.id===C)&&v("")},[_e,C]),ee.useEffect(()=>{if(x&&!he.some(re=>re.id===x)){B("");return}if(!x&&F){const re=he.find(we=>we.engine_kind===F);re&&B(re.id)}},[he,F,x]),ee.useEffect(()=>{if(!He)return;const re=window.setInterval(()=>{ae(we=>Tl(we,Ne)),Ee(we=>we+1)},220);return()=>window.clearInterval(re)},[ye,He]),ee.useEffect(()=>{if(!X||xt===0||E.current)return;const re=window.setTimeout(async()=>{try{const we=eo(c,X),Ge=bu(ci(X.params,ci(lo(ye,G,K,Ie,F,Ce,!1),{caClass:me})),we);await gt(`/api/ca/preset-trees/${X.tree_id}/nodes/${X.id}`,{method:"PATCH",body:JSON.stringify({name:N,description:L.trim()||null,params:Ge})}),f(it=>it.map(lt=>lt.id===X.id?{...lt,name:N,description:L.trim()||null,params:Ge}:lt)),W("Preset saved")}catch(we){W(we instanceof Error?we.message:"Preset autosave failed")}},450);return()=>window.clearTimeout(re)},[Ce,me,xt,F,G,L,N,c,K,ye,X]);function Qe(){E.current||I(re=>re+1)}async function Je(re){E.current=!0,nt(!1);const[we,Ge]=await Promise.all([gt(`/api/ca/preset-trees/${i}/nodes/${re}`),gt(`/api/ca/preset-trees/${i}/nodes/${re}/resolved`)]);T(we.id),zt(!1),A(we.name),j(we.description??"");const it=Ml(Ge.params);$(it?.dimensions??2),ge(typeof it?.states=="number"?it.states:it?.states.length??2),H(Ge.params.renderer?.id??"2d-canvas"),ne(Ge.params.simulation?.neighborhoodId??"moore"),xe(Ge.params.simulation?.ruleId??"B3/S23"),Ue(Sx(Ge.params));const lt=Ge.params.simulation?.engineId??"";J(lt),B(S.find(vt=>vt.engine_kind===lt)?.id??""),v(""),Ye(""),ae(Dl(Ge.params.simulation?.initialCondition?.cells)),Ee(0),W(`Loaded preset "${we.name}"`),window.setTimeout(()=>{E.current=!1,I(0),zt(!1)},0)}function pt(re){Je(re.id),window.matchMedia("(max-width: 820px)").matches&&St(!1)}function Z(){window.matchMedia("(max-width: 820px)").matches&&Ht(!1),St(!0)}function Pe(){window.matchMedia("(max-width: 820px)").matches&&St(!1),Ht(!0)}async function Se(re="shot"){const we=Date.now(),Ge=wp(c,null),it=re==="chapter"?`Group ${Ge.length+1}`:`Preset ${Ge.length+1}`;try{const lt=await gt(`/api/ca/preset-trees/${i}/nodes`,{method:"POST",body:JSON.stringify({parentId:null,slug:`${no(it)}-${we}`,name:it,kind:re,description:null,sortOrder:px(c,null),params:BR({rootName:it,rendererId:K,neighborhoodId:G,dimensions:2,states:2,ruleId:ye})})});await ze(),await Je(lt.id),W(`Created preset "${lt.name}"`)}catch(lt){W(lt instanceof Error?lt.message:"Preset create failed")}}async function Be(re,we="shot"){const Ge=Date.now(),it=we==="chapter"?`${re.name} group`:`${re.name} variant`;try{const lt=await gt(`/api/ca/preset-trees/${i}/nodes`,{method:"POST",body:JSON.stringify({parentId:re.id,slug:`${no(it)}-${Ge}`,name:it,kind:we,description:null,sortOrder:px(c,re.id),params:{}})});await ze(),await Je(lt.id),W(`Created child preset "${lt.name}"`)}catch(lt){W(lt instanceof Error?lt.message:"Preset create failed")}}async function ke(re){const we=new Set([re.id]);let Ge=!0;for(;Ge;){Ge=!1;for(const vt of c)vt.parent_id&&we.has(vt.parent_id)&&!we.has(vt.id)&&(we.add(vt.id),Ge=!0)}const lt=p.filter(vt=>we.has(vt.node_id)).reduce((vt,In)=>vt+In.scene_count,0);if(lt>0){const vt=we.size>1?`This preset contains ${lt} slide reference${lt===1?"":"s"} in its subtree. Detach them before deleting it.`:`This preset is assigned to ${lt} slide${lt===1?"":"s"}. Detach it before deleting.`;return W(vt),!1}try{const vt=await fetch(`/api/ca/preset-trees/${re.tree_id}/nodes/${re.id}`,{method:"DELETE"});if(!vt.ok){const hn=await vt.json().catch(()=>null);throw new Error(hn?.error??"Preset could not be deleted.")}re.id===b&&(T(""),A("Untitled preset"),j(""));const In=await ze(),Zt=In.find(hn=>hn.parent_id===re.parent_id)??In[0];return Zt&&await Je(Zt.id),W(`Deleted preset "${re.name}"`),!0}catch(vt){return W(vt instanceof Error?vt.message:"Preset delete failed"),!1}}async function q(re,we){const Ge=wp(c,re.parent_id),it=Ge.findIndex(Zt=>Zt.id===re.id),lt=it+we;if(it===-1||lt<0||lt>=Ge.length)return;const vt=[...Ge],[In]=vt.splice(it,1);vt.splice(lt,0,In);try{const Zt=await Promise.all(vt.map((yn,fn)=>gt(`/api/ca/preset-trees/${yn.tree_id}/nodes/${yn.id}`,{method:"PATCH",body:JSON.stringify({sortOrder:fn})}))),hn=new Map(Zt.map(yn=>[yn.id,yn]));f(yn=>yn.map(fn=>hn.get(fn.id)??fn)),W(`Moved "${re.name}"`)}catch(Zt){W(Zt instanceof Error?Zt.message:"Preset reorder failed")}}async function Me(re,we,Ge){let it=La(re.params,we,Ge);const lt=we.join(".")==="caClass.dimensions"||we.join(".")==="caClass.states"||we.join(".")==="caClass.neighborhoodId",vt=[];if(lt){const Zt=ci(eo(c,re),it),hn=Ml(Zt),yn=Zt.simulation?.engineId,fn=S.find(Kt=>Kt.engine_kind===yn),Gn=Zt.renderer?.id,Bn=Nh(hn);if(fn&&!Oa(fn,hn)&&(it=La(it,["simulation","engineId"],null),vt.push(`Evolution function "${fn.name}" was unset`)),typeof Gn=="string"&&!Bn.some(Kt=>Kt.id===Gn)){const Kt=Bn[0];it=La(it,["renderer","id"],Kt?.id??null),vt.push(Kt?`Renderer changed to "${Kt.label}"`:"No renderer supports this dimensionality and state space")}const Ti=h.find(Kt=>Kt.id===C);re.id===b&&Ti&&!Oa(Ti,hn)&&(v(""),vt.push(`Initial condition generator "${Ti.name}" was unset`))}const In=await gt(`/api/ca/preset-trees/${re.tree_id}/nodes/${re.id}`,{method:"PATCH",body:JSON.stringify({params:it})});f(Zt=>Zt.map(hn=>hn.id===re.id?In:hn)),re.id===b&&await Je(re.id),vt.length>0&&Ye(vt.join(". ")),W(`Saved ${we.join(".")} on "${re.name}"`)}async function De(re,we){const Ge=await gt(`/api/ca/preset-trees/${re.tree_id}/nodes/${re.id}`,{method:"PATCH",body:JSON.stringify({name:we})});f(it=>it.map(lt=>lt.id===re.id?Ge:lt)),re.id===b&&A(Ge.name),W(`Renamed preset to "${Ge.name}"`)}async function ft(re,we){const Ge=Ey(re.params,we),it=await gt(`/api/ca/preset-trees/${re.tree_id}/nodes/${re.id}`,{method:"PATCH",body:JSON.stringify({params:Ge})});f(lt=>lt.map(vt=>vt.id===re.id?it:vt)),re.id===b&&await Je(re.id),W(`Unset ${we.join(".")} on "${re.name}"`)}async function rt(){if(!X||!Oe)return;const re=_e.find(we=>we.id===C);if(re)try{nt(!1);const we=Math.max(0,Math.min(1,P)),Ge=ab(re.generator_kind,{settings:Ne,caClass:Oe,params:{density:we,seed:O}}),it=eo(c,X),lt=bu(ci(X.params,{simulation:{initialCondition:Ge}}),it),vt=await gt(`/api/ca/preset-trees/${X.tree_id}/nodes/${X.id}`,{method:"PATCH",body:JSON.stringify({params:lt})});f(In=>In.map(Zt=>Zt.id===vt.id?vt:Zt)),ae(Dl(Ge.cells)),zt(!1),Ee(0),W(`Generated initial condition on "${X.name}"`)}catch(we){W(we instanceof Error?we.message:"ICG apply failed")}}function Nt(re){const we=he.find(Ge=>Ge.id===re);if(B(re),!we){J(""),X&&(f(Ge=>Ge.map(it=>it.id===X.id?{...it,params:La(it.params,["simulation","engineId"],null)}:it)),Qe());return}if(J(we.engine_kind),typeof we.default_params.ruleId=="string"&&xe(we.default_params.ruleId),typeof we.default_params.rendererId=="string"&&je.some(Ge=>Ge.id===we.default_params.rendererId)&&H(we.default_params.rendererId),X){Me(X,["simulation","engineId"],we.engine_kind);for(const[Ge,it]of Object.entries(we.default_params))Me(X,by(Ge),it)}Qe()}function Hn(re,we){if(!X)return;const Ge=re.join(".");Ge==="simulation.ruleId"&&typeof we=="string"&&xe(we),Ge==="renderer.id"&&typeof we=="string"&&H(we),Ge==="simulation.grid.boundary"&&(we==="wrap"||we==="mirror"||we==="fixed")&&Ue(we),Ge==="simulation.grid.wrap"&&typeof we=="boolean"&&Ue(we?"wrap":"fixed"),Me(X,re,we)}function ua(re,we,Ge=G){if(!X)return;const it={dimensions:re,states:we,neighborhoodId:Ge},lt=[];let vt=K,In=!1;const Zt=S.find(fn=>fn.engine_kind===F);Zt&&!Oa(Zt,it)&&(In=!0,J(""),B(""),lt.push(`Evolution function "${Zt.name}" was unset`));const hn=h.find(fn=>fn.id===C);hn&&!Oa(hn,it)&&(v(""),lt.push(`Initial condition generator "${hn.name}" was unset`));const yn=Nh(it);yn.some(fn=>fn.id===K)||(vt=yn[0]?.id??"",H(vt),lt.push(vt?`Renderer changed to "${yn[0].label}"`:"No renderer supports this dimensionality and state space")),$(re),ge(we),ne(Ge),Ye(lt.join(". ")),f(fn=>fn.map(Gn=>{if(Gn.id!==X.id)return Gn;let Bn=La(Gn.params,["caClass"],it);return Bn=La(Bn,["simulation","neighborhoodId"],Ge),In&&(Bn=La(Bn,["simulation","engineId"],null)),vt!==K&&(Bn=La(Bn,["renderer","id"],vt)),{...Gn,params:Bn}})),Qe()}function Va(re){nt(!1),Ee(0),ae(re),zt(!0)}async function ka(){if(!(!X||ht))try{Et(!0),nt(!1);const re=eo(c,X),we=bu(ci(X.params,{simulation:{initialCondition:{type:"cells",cells:$p(Ie)}}}),re),Ge=await gt(`/api/ca/preset-trees/${X.tree_id}/nodes/${X.id}`,{method:"PATCH",body:JSON.stringify({params:we})});f(it=>it.map(lt=>lt.id===Ge.id?Ge:lt)),zt(!1),Ee(0),W(`Saved initial condition on "${X.name}"`)}catch(re){W(re instanceof Error?re.message:"Initial condition save failed")}finally{Et(!1)}}function ja(){nt(!1),ae(re=>Tl(re,Ne)),Ee(re=>re+1)}return g.jsxs("main",{className:"studio-shell preset-studio-shell",children:[g.jsxs("header",{className:"topbar preset-studio-topbar",children:[g.jsxs("div",{className:"preset-library-heading",children:[g.jsx("p",{className:"eyebrow",children:"Preset Library"}),g.jsx("h1",{children:s?.name??"Library"}),g.jsx("button",{className:"header-back-button",type:"button",onClick:()=>Pi(e??mo("cas")),children:"Back"})]}),g.jsxs("div",{className:"topbar-actions",children:[g.jsx("div",{className:"status",children:It}),g.jsx(za,{})]})]}),g.jsxs("section",{className:`preset-studio-workspace${yt?" tree-open":""}${Mt?" inspector-open":""}`,children:[g.jsx("button",{"aria-label":"Close preset drawer",className:"drawer-scrim tree-scrim",type:"button",onClick:()=>St(!1)}),g.jsxs("aside",{className:"studio-drawer preset-tree-drawer",children:[g.jsxs("div",{className:"drawer-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Presets"}),g.jsx("h2",{children:"Library tree"})]}),g.jsx("button",{"aria-label":"Close preset drawer",className:"icon-button drawer-close",type:"button",onClick:()=>St(!1),children:"×"}),g.jsx(za,{})]}),g.jsxs("div",{className:"drawer-scroll",children:[g.jsxs("div",{className:"root-selector",children:[g.jsx("button",{className:"primary",type:"button",onClick:()=>{Se()},children:"New preset"}),g.jsx("button",{type:"button",onClick:()=>{Se("chapter")},children:"New group"})]}),g.jsx("div",{className:"tree-list",children:g.jsx(xR,{engines:S,nodes:c,selectedNodeId:b,usedNodeIds:se,onCreateChild:re=>{Be(re,"shot")},onCreateGroup:re=>{Be(re,"chapter")},onDelete:re=>ke(re),onMove:(re,we)=>{q(re,we)},onRename:(re,we)=>De(re,we),onSelect:pt,onSet:(re,we,Ge)=>{Me(re,we,Ge)},onUnset:(re,we)=>{ft(re,we)}})})]})]}),g.jsxs("section",{className:"preset-stage",children:[g.jsxs("div",{className:"preset-stage-toolbar",children:[g.jsxs("div",{className:"preset-stage-title",children:[g.jsx("button",{type:"button",onClick:Z,children:"Presets"}),g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Preset Preview"}),g.jsx("h2",{children:X?N:"Select a preset"})]})]}),g.jsxs("div",{className:"button-row",children:[g.jsx("button",{type:"button",onClick:ja,children:"Step"}),g.jsx("button",{className:"primary playback-button",type:"button",onClick:()=>nt(re=>!re),children:He?"⏸":"▶"}),g.jsx("button",{type:"button",onClick:Pe,children:"Inspector"})]})]}),g.jsxs("div",{className:`preset-renderer-stage${Ke?" ic-dirty":""}`,children:[Ke?g.jsxs("div",{className:"ic-dirty-banner",role:"status",children:[g.jsx("span",{children:"Unsaved initial condition"}),g.jsx("button",{className:"primary",disabled:!X||ht,type:"button",onClick:()=>{ka()},children:ht?"Saving...":"Save"})]}):null,g.jsx(Fu,{caption:"",cells:Ie,settings:Ne,onCellsChange:Va})]}),g.jsxs("footer",{className:"metrics preset-stage-metrics",children:[g.jsxs("span",{children:["Generation ",g.jsx("strong",{children:Ae})]}),g.jsxs("span",{children:["Live cells ",g.jsx("strong",{children:my(Ie)})]}),g.jsxs("span",{children:["Preset ",g.jsx("strong",{children:b?b.slice(0,8):"none"})]})]})]}),g.jsx("button",{"aria-label":"Close inspector",className:"drawer-scrim inspector-scrim",type:"button",onClick:()=>Ht(!1)}),g.jsxs("aside",{className:"studio-drawer preset-inspector-drawer",children:[g.jsxs("div",{className:"drawer-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Inspector"}),g.jsx("h2",{children:X?N:"No preset selected"})]}),g.jsx("button",{"aria-label":"Close inspector",className:"icon-button drawer-close",type:"button",onClick:()=>Ht(!1),children:"×"}),g.jsx(za,{})]}),g.jsxs("div",{className:"inspector-tabs",role:"tablist","aria-label":"Preset inspector sections",children:[g.jsx("button",{className:Gt==="ca"?"active":"",role:"tab",type:"button",onClick:()=>st("ca"),children:"CA"}),g.jsx("button",{className:Gt==="initial"?"active":"",role:"tab",type:"button",onClick:()=>st("initial"),children:"Initial State"}),g.jsx("button",{className:Gt==="display"?"active":"",role:"tab",type:"button",onClick:()=>st("display"),children:"Display"})]}),g.jsxs("div",{className:"drawer-scroll inspector-body",children:[Gt==="ca"?g.jsxs("div",{className:"inspector-section",children:[z?g.jsx("div",{className:"compatibility-warning",role:"alert",children:z}):null,g.jsxs("section",{className:"preset-modal-stage inspector-ca-stage",children:[g.jsxs("div",{className:"preset-modal-stage-heading",children:[g.jsx("span",{children:"1"}),g.jsxs("div",{children:[g.jsx("h3",{children:"CA space"}),g.jsx("p",{children:"Choose dimensions, state count, and neighbourhood first."})]})]}),g.jsxs("label",{children:["Preset name",g.jsx("input",{disabled:!X,value:N,onChange:re=>{A(re.target.value),Qe()}})]}),g.jsxs("label",{children:["Description",g.jsx("textarea",{disabled:!X,value:L,onChange:re=>{j(re.target.value),Qe()}})]}),g.jsxs("div",{className:"preset-modal-class-grid inspector-ca-class-grid",children:[g.jsxs("label",{children:["Dimensions",g.jsxs("select",{disabled:!X,value:V,onChange:re=>{ua(Number(re.target.value),pe,G)},children:[g.jsx("option",{value:1,children:"1D"}),g.jsx("option",{value:2,children:"2D"}),g.jsx("option",{value:3,children:"3D"})]})]}),g.jsxs("label",{children:["States",g.jsx("input",{disabled:!X,min:2,step:1,type:"number",value:pe,onChange:re=>ua(V,Math.max(2,Number(re.target.value)||2),G)})]}),g.jsxs("label",{children:["Neighbourhood",g.jsxs("select",{disabled:!X,value:G,onChange:re=>{ua(V,pe,re.target.value)},children:[g.jsx("option",{value:"moore",children:"Moore"}),g.jsx("option",{value:"von-neumann",children:"Von Neumann"})]})]})]})]}),g.jsxs("section",{className:"preset-modal-stage inspector-ca-stage",children:[g.jsxs("div",{className:"preset-modal-stage-heading",children:[g.jsx("span",{children:"2"}),g.jsxs("div",{children:[g.jsx("h3",{children:"Evolution engine"}),g.jsx("p",{children:"Only engines that support this CA space can be selected."})]})]}),g.jsxs("label",{children:["Engine",g.jsxs("select",{disabled:!X,value:Le?.id??"",onChange:re=>Nt(re.target.value),children:[g.jsx("option",{value:"",children:"Select evolution function"}),he.map(re=>g.jsx("option",{value:re.id,children:re.name},re.id))]})]}),Le?g.jsx("small",{className:"param-empty",children:Le.license?`License: ${Le.license}`:"No license metadata"}):g.jsx("p",{className:"param-empty",children:he.length>0?"Select an evolution function for this preset.":"No matching engine for this preset class."})]}),g.jsxs("section",{className:"preset-modal-stage inspector-ca-stage",children:[g.jsxs("div",{className:"preset-modal-stage-heading",children:[g.jsx("span",{children:"3"}),g.jsxs("div",{children:[g.jsx("h3",{children:"Engine settings"}),g.jsx("p",{children:"Controls are supplied by the selected engine schema."})]})]}),g.jsx(YR,{disabled:!X,engine:Le,settings:Ne,onSet:Hn})]})]}):null,Gt==="initial"?g.jsxs("div",{className:"inspector-section",children:[g.jsxs("div",{className:"button-row initial-condition-actions",children:[g.jsx("button",{type:"button",onClick:()=>Va(sr()),children:"Clear canvas"}),g.jsx("button",{className:"primary",disabled:!X||!Ke||ht,type:"button",onClick:()=>{ka()},children:ht?"Saving...":"Save initial condition"})]}),Ke?g.jsx("p",{className:"param-empty",children:"Initial condition has unsaved canvas edits."}):g.jsx("p",{className:"param-empty",children:"Canvas edits are saved explicitly so preview playback stays temporary."}),_e.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("label",{children:["Generator",g.jsxs("select",{value:C,onChange:re=>{const we=_e.find(Ge=>Ge.id===re.target.value);v(re.target.value),typeof we?.default_params.density=="number"&&D(we.default_params.density),typeof we?.default_params.seed=="string"&&U(we.default_params.seed)},children:[g.jsx("option",{value:"",children:"Select generator"}),_e.map(re=>g.jsx("option",{value:re.id,children:re.name},re.id))]})]}),g.jsxs("div",{className:"icg-controls",children:[g.jsxs("label",{children:["Density",g.jsx("input",{max:1,min:0,step:.01,type:"range",value:P,onChange:re=>D(Number(re.target.value))})]}),g.jsxs("strong",{children:[Math.round(P*100),"%"]})]}),g.jsxs("label",{children:["Seed",g.jsx("input",{value:O,onChange:re=>U(re.target.value)})]}),g.jsx("button",{className:"primary",disabled:!X||!C,type:"button",onClick:()=>{rt()},children:"Generate initial condition"})]}):g.jsx("p",{className:"param-empty",children:"No matching generator for this preset class."})]}):null,Gt==="display"?g.jsxs("div",{className:"inspector-section",children:[g.jsxs("label",{children:["Renderer",g.jsx("select",{disabled:!X,value:K,onChange:re=>{H(re.target.value),Qe()},children:je.map(re=>g.jsx("option",{value:re.id,children:re.label},re.id))})]}),je.length===0?g.jsx("p",{className:"param-empty",children:"No renderer supports this dimensionality and state space."}):null,g.jsx("p",{className:"param-empty",children:"Renderer-specific display controls will appear in this inspector."})]}):null]})]})]})]})}function JR({assignedNodeId:a,assignedNodeName:e,autoplayOnSlideChange:i,caption:s,scene:l,slideTitle:c,onAutoplayChange:f,onCaptionChange:p,onClose:m,onSelectCa:h,onSlideTitleChange:y}){return g.jsx("div",{className:"modal-backdrop slide-modal-backdrop",role:"presentation",onMouseDown:m,children:g.jsxs("section",{"aria-modal":"true",className:"property-modal slide-metadata-modal",role:"dialog",onMouseDown:S=>S.stopPropagation(),children:[g.jsxs("header",{className:"property-modal-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Slide Metadata"}),g.jsx("h2",{children:l.scene.title})]}),g.jsx("button",{type:"button",onClick:m,children:"Close"})]}),g.jsxs("div",{className:"slide-metadata-body",children:[g.jsxs("label",{children:["Slide name",g.jsx("input",{value:c,onChange:S=>y(S.target.value)})]}),g.jsxs("label",{children:["Caption",g.jsx("textarea",{value:s,onChange:S=>p(S.target.value)})]}),g.jsxs("label",{className:"toggle-field",children:[g.jsx("input",{checked:i,type:"checkbox",onChange:S=>f(S.target.checked)}),"Autoplay on slide change"]}),g.jsxs("section",{className:"slide-ca-asset",children:[g.jsxs("div",{children:[g.jsx("span",{children:"CA preset"}),g.jsx("strong",{children:e??"No CA selected"}),g.jsx("small",{children:a?a.slice(0,8):"Select a reusable preset asset"})]}),g.jsx("button",{className:"primary",type:"button",onClick:h,children:"Select CA"})]}),g.jsxs("div",{className:"slide-metadata-grid",children:[g.jsxs("span",{children:[g.jsx("strong",{children:"Order"}),g.jsx("small",{children:l.scene.order_index})]}),g.jsxs("span",{children:[g.jsx("strong",{children:"Apply mode"}),g.jsx("small",{children:l.scene.apply_mode})]}),g.jsxs("span",{children:[g.jsx("strong",{children:"Assigned node"}),g.jsx("small",{children:a?a.slice(0,8):"none"})]}),g.jsxs("span",{children:[g.jsx("strong",{children:"Tree"}),g.jsx("small",{children:l.scene.preset_tree_id?.slice(0,8)??"none"})]})]})]})]})})}function e2({assignedNodeId:a,loading:e,nodes:i,presetTrees:s,resolvedNode:l,selectedNode:c,selectedTreeId:f,onClose:p,onEditSelected:m,onSelectNode:h,onSelectTree:y,onUseSelected:S}){const _=Dl(l?.params.simulation?.initialCondition?.cells);return ee.useEffect(()=>{function b(T){T.key==="Escape"&&p()}return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[p]),g.jsx("div",{className:"modal-backdrop ca-asset-modal-backdrop",role:"presentation",onMouseDown:p,children:g.jsxs("section",{"aria-modal":"true",className:"property-modal ca-asset-modal",role:"dialog",onMouseDown:b=>b.stopPropagation(),children:[g.jsxs("header",{className:"property-modal-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"CA Assets"}),g.jsx("h2",{children:"Select a preset"})]}),g.jsx("button",{type:"button",onClick:p,children:"Close"})]}),g.jsxs("div",{className:"ca-asset-layout",children:[g.jsxs("aside",{className:"ca-asset-browser",children:[g.jsxs("label",{children:["CA library",g.jsx("select",{value:f,onChange:b=>y(b.target.value),children:s.map(b=>g.jsxs("option",{value:b.id,children:[b.name," (",b.node_count,")"]},b.id))})]}),e?g.jsx("p",{className:"empty",children:"Loading CA presets..."}):g.jsx(pR,{assignedNodeId:a,nodes:i,selectedNodeId:c?.id,onSelect:h})]}),g.jsxs("section",{className:"ca-asset-preview",children:[g.jsxs("div",{className:"ca-asset-preview-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Preview"}),g.jsx("h3",{children:c?.name??"Select a CA preset"}),c?.description?g.jsx("p",{children:c.description}):null]}),l?g.jsxs("small",{children:[l.params.caClass?.dimensions??"?","D · ",String(l.params.caClass?.states??"?")," states"]}):null]}),g.jsx("div",{className:"ca-asset-preview-stage",children:l?g.jsx(Fu,{caption:"",cells:_,settings:l.params,onCellsChange:()=>{}}):g.jsx("p",{className:"empty",children:"Choose a preset from the tree to inspect it."})}),g.jsxs("div",{className:"ca-asset-actions",children:[g.jsx("button",{type:"button",onClick:p,children:"Cancel"}),g.jsx("button",{disabled:!c||c.kind==="chapter",type:"button",onClick:m,children:"Edit CA"}),g.jsx("button",{className:"primary",disabled:!c||c.kind==="chapter",type:"button",onClick:S,children:"Use this CA"})]})]})]})]})})}function t2({deckId:a}){const[e,i]=ee.useState(null),[s,l]=ee.useState(0),[c,f]=ee.useState(()=>lo("B3/S23","moore","2d-canvas",sr())),[p,m]=ee.useState(()=>sr()),[h,y]=ee.useState(0),[S,_]=ee.useState(!1),[b,T]=ee.useState("Loading viewer..."),C=ee.useRef(c),v=ee.useRef(s),x=e?.scenes[s]??null,B=ee.useMemo(()=>hx(c,p),[p,c]);ee.useEffect(()=>{C.current=c},[c]),ee.useEffect(()=>{v.current=s},[s]);function P(U,N,A={}){const L=A.forceReinitialize===!0||U.scene.apply_mode!=="patch_existing"&&U.scene.requires_previous_scene!==!0;l(N),f(U.params),L&&(m(Dl(U.params.simulation?.initialCondition?.cells)),y(0)),_(GR(U)),T(U.scene.title)}const D=ee.useCallback((U,N={})=>{const A=e?.scenes??[];if(A.length===0)return;const L=Math.min(Math.max(U,0),A.length-1);P(A[L],L,N)},[e]),O=ee.useCallback(()=>{m(U=>Tl(U,hx(C.current,U))),y(U=>U+1)},[]);return ee.useEffect(()=>{let U=!1;async function N(){try{const A=await gt(`/api/ca/decks/${a}/resolved`);if(U)return;i(A),A.scenes[0]?P(A.scenes[0],0,{forceReinitialize:!0}):T("Deck has no slides")}catch(A){U||T(A instanceof Error?A.message:"Viewer load failed")}}return N(),()=>{U=!0}},[a]),ee.useEffect(()=>{if(!S)return;const U=window.setInterval(O,220);return()=>window.clearInterval(U)},[S,O]),ee.useEffect(()=>{function U(N){if(!gy(N.target)){if(N.key==="ArrowRight"||N.key==="ArrowDown"){N.preventDefault(),D(v.current+1);return}if(N.key==="ArrowLeft"||N.key==="ArrowUp"){N.preventDefault(),D(v.current-1);return}if(N.key===" "){N.preventDefault(),_(A=>!A);return}if(N.key==="."||N.key.toLowerCase()==="s"){N.preventDefault(),_(!1),O();return}N.key.toLowerCase()==="r"&&(N.preventDefault(),D(v.current,{forceReinitialize:!0}))}}return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[D,O]),g.jsx("main",{className:"viewer-shell",children:g.jsxs("section",{className:"viewer-stage","aria-label":x?.scene.title??b,children:[g.jsx(Fu,{caption:HR(x),cells:p,settings:B,onCellsChange:()=>{}}),g.jsxs("div",{className:"viewer-rec-status","aria-hidden":"true",children:[g.jsx("span",{children:e?.deck.title??"CA Deck"}),g.jsx("span",{children:x?`${s+1}/${e?.scenes.length??0}`:b}),g.jsx("span",{children:S?"REC PLAY":"REC HOLD"}),g.jsxs("span",{children:["G",h]})]})]})})}function n2({deckId:a,initialSceneId:e}){const[i,s]=ee.useState(null),[l,c]=ee.useState("Deck editor"),[f,p]=ee.useState(null),[m,h]=ee.useState([]),[y,S]=ee.useState([]),[_,b]=ee.useState(""),[T,C]=ee.useState(!1),[v,x]=ee.useState(!1),[B,P]=ee.useState(""),[D,O]=ee.useState([]),[U,N]=ee.useState(""),[A,L]=ee.useState(null),[j,V]=ee.useState(!1),[$,pe]=ee.useState(""),[ge,K]=ee.useState("Untitled slide"),[H,G]=ee.useState("Glider"),[ne,ye]=ee.useState(""),[xe,F]=ee.useState(!1),[J,Ce]=ee.useState("2d-canvas"),[Ue,Ie]=ee.useState("moore"),[ae,Ae]=ee.useState("B3/S23"),[Ee,He]=ee.useState("wrap"),[nt,Ke]=ee.useState(()=>DR()),[zt,ht]=ee.useState(0),[Et,yt]=ee.useState(!1),[St,Mt]=ee.useState("Loading deck..."),Ht=ee.useRef(!1),Gt=ee.useRef(!1),st=f?.scenes.find(q=>q.scene.id===_)??null,It=f?.scenes.findIndex(q=>q.scene.id===_)??-1;oo(i);const W=f?.scenes.length??0,z=It>0,Ye=It>=0&&Itq.id===$)??null,I=st?.scene.preset_node_id,E=D.find(q=>q.id===U)??null,X=xt?ci(ci(eo(y,xt),xt.params),lo(ae,Ue,J,nt,void 0,Ee)):lo(ae,Ue,J,nt,void 0,Ee),se=ee.useCallback(async()=>{const q=await gt(`/api/ca/decks/${a}`),Me=await gt(`/api/ca/decks/${a}/resolved`);return Gt.current=!0,s(q),c(q.title),p(Me),window.setTimeout(()=>{Gt.current=!1},0),{deck:q,resolvedDeck:Me}},[a]);async function me(q){const Me=await gt(`/api/ca/preset-trees/${q}/nodes`);S(Me)}async function Ne(){const q=await gt("/api/ca/preset-trees");return h(q),q}async function Oe(q,Me){const De=oo(q);if(De.presetTreeId)return await me(De.presetTreeId),De;const ft=Me.scenes[0];if(ft?.scene.preset_tree_id){const rt={presetTreeId:ft.scene.preset_tree_id,rootNodeId:void 0,rendererId:ft.params.renderer?.id??"2d-canvas",neighborhoodId:ft.params.simulation?.neighborhoodId??"moore",ruleId:ft.params.simulation?.ruleId??"B3/S23"},Nt=await gt(`/api/ca/decks/${q.id}`,{method:"PATCH",body:JSON.stringify({params:UR(q,rt)})});return s(Nt),await me(rt.presetTreeId),Mt("Repaired deck metadata from existing slides"),rt}return S([]),De}ee.useEffect(()=>{async function q(){try{const Me=await se();await Ne();const De=await Oe(Me.deck,Me.resolvedDeck),ft=Me.resolvedDeck.scenes.find(rt=>rt.scene.id===e)??Me.resolvedDeck.scenes[0];ft?he(ft):(Ce(De.rendererId??"2d-canvas"),Ie(De.neighborhoodId??"moore"),Ae(De.ruleId??"B3/S23"),He("wrap"),Mt(De.presetTreeId?"Deck ready. Add the first slide.":"Deck ready. Add the first slide and select a CA asset."))}catch(Me){Mt(Me instanceof Error?Me.message:"Deck load failed")}}q()},[a,e,se]),ee.useEffect(()=>{if(!Et)return;const q=window.setInterval(()=>{Ke(Me=>Tl(Me,X)),ht(Me=>Me+1)},220);return()=>window.clearInterval(q)},[ae,Et]),ee.useEffect(()=>{if(!i||Gt.current||l===i.title)return;const q=window.setTimeout(async()=>{const Me=l.trim()||"Untitled deck";try{const De=await gt(`/api/ca/decks/${i.id}`,{method:"PATCH",body:JSON.stringify({title:Me})});s(De),c(De.title),Mt("Deck name saved")}catch(De){Mt(De instanceof Error?De.message:"Deck name save failed")}},450);return()=>window.clearTimeout(q)},[i,l]),ee.useEffect(()=>{if(!st||Ht.current)return;const q=ge.trim()||"Untitled slide",Me=typeof st.scene.params.caption=="string"?st.scene.params.caption:"",De=st.scene.params.autoplayOnSlideChange===!0;if(st.scene.title===q&&Me===ne&&De===xe)return;const ft=window.setTimeout(async()=>{try{await gt(`/api/ca/scenes/${st.scene.id}`,{method:"PATCH",body:JSON.stringify({title:q,params:{...st.scene.params,caption:ne,autoplayOnSlideChange:xe}})}),p(rt=>rt&&{...rt,scenes:rt.scenes.map(Nt=>Nt.scene.id===st.scene.id?{...Nt,scene:{...Nt.scene,title:q,params:{...Nt.scene.params,caption:ne,autoplayOnSlideChange:xe}}}:Nt)}),Mt("Slide settings saved")}catch(rt){Mt(rt instanceof Error?rt.message:"Slide settings autosave failed")}},450);return()=>window.clearTimeout(ft)},[st,xe,ne,ge]);async function _e(q,Me,De,ft={}){Ht.current=!0,yt(!1);const[rt,Nt,Hn]=await Promise.all([gt(`/api/ca/preset-trees/${q}/nodes/${Me}`),gt(`/api/ca/preset-trees/${q}/nodes/${Me}/resolved`),gt(`/api/ca/preset-trees/${q}/nodes`)]);S(Hn),pe(Me),G(rt.name||De||"Untitled node"),Ce(Nt.params.renderer?.id??"2d-canvas"),Ie(Nt.params.simulation?.neighborhoodId??"moore"),Ae(Nt.params.simulation?.ruleId??"B3/S23"),He(Sx(Nt.params)),Ke(Dl(Nt.params.simulation?.initialCondition?.cells)),ht(0),Mt(`Loaded node "${rt.name}"`),window.setTimeout(()=>{Ht.current=!1,yt(ft.runAfterLoad===!0)},0)}function he(q){Ht.current=!0;const Me=q.scene.params.autoplayOnSlideChange===!0;if(yt(!1),b(q.scene.id),K(q.scene.title),ye(typeof q.scene.params.caption=="string"?q.scene.params.caption:""),F(Me),q.scene.preset_tree_id&&q.scene.preset_node_id){_e(q.scene.preset_tree_id,q.scene.preset_node_id,q.scene.title,{runAfterLoad:Me});return}pe(""),G("No CA preset"),Ke(sr()),ht(0),Mt(`Loaded empty slide "${q.scene.title}"`),window.setTimeout(()=>{Ht.current=!1},0)}function Le(q){he(q),C(!0)}async function je(q){N(q.id),V(!0);try{const Me=await gt(`/api/ca/preset-trees/${q.tree_id}/nodes/${q.id}/resolved`);L(Me)}catch(Me){L(null),Mt(Me instanceof Error?Me.message:"CA preview failed")}finally{V(!1)}}async function ze(q,Me){if(!q){P(""),O([]),N(""),L(null);return}P(q),V(!0);try{const De=await gt(`/api/ca/preset-trees/${q}/nodes`);O(De);const rt=De.find(Nt=>Nt.id===Me)??De.find(Nt=>Nt.kind!=="chapter")??null;rt?(N(rt.id),L(await gt(`/api/ca/preset-trees/${q}/nodes/${rt.id}/resolved`))):(N(""),L(null))}catch(De){O([]),N(""),L(null),Mt(De instanceof Error?De.message:"CA library load failed")}finally{V(!1)}}function Fe(){const q=st?.scene.preset_tree_id??m[0]?.id??"";C(!1),x(!0),ze(q,st?.scene.preset_node_id??void 0)}async function Qe(){if(!E||E.kind==="chapter"||!st)return;await gt(`/api/ca/scenes/${st.scene.id}`,{method:"PATCH",body:JSON.stringify({presetTreeId:E.tree_id,presetNodeId:E.id,params:{...st.scene.params,caption:ne,autoplayOnSlideChange:xe}})});const Me=(await se()).resolvedDeck.scenes.find(De=>De.scene.id===st.scene.id);Me&&he(Me),x(!1),Mt(`Assigned "${E.name}" to selected slide`)}async function Je(){if(st)try{yt(!1),Mt(`Deleting slide "${st.scene.title}"...`);const q=st.scene.id,Me=st.scene.title,De=f?.scenes.findIndex(Nt=>Nt.scene.id===q)??0;await fetch(`/api/ca/scenes/${q}`,{method:"DELETE"}).then(Nt=>{if(!Nt.ok)throw new Error("Unable to delete slide")});const ft=await se(),rt=ft.resolvedDeck.scenes[Math.min(Math.max(De,0),ft.resolvedDeck.scenes.length-1)];rt?he(rt):(b(""),K("Untitled slide"),ye(""),F(!1)),Mt(`Deleted slide "${Me}". Preset node kept.`)}catch(q){Mt(q instanceof Error?q.message:"Slide delete failed")}}async function pt(q){if(!(!i||q.length===0))try{Mt("Reordering slides...");const Me=1e5;await Promise.all(q.map((De,ft)=>gt(`/api/ca/scenes/${De.scene.id}`,{method:"PATCH",body:JSON.stringify({orderIndex:Me+ft})}))),await Promise.all(q.map((De,ft)=>gt(`/api/ca/scenes/${De.scene.id}`,{method:"PATCH",body:JSON.stringify({orderIndex:ft+1})}))),await se(),Mt("Slides reordered")}catch(Me){Mt(Me instanceof Error?Me.message:"Slide reorder failed")}}async function Z(){if(!i)return;Mt("Creating slide...");const q=W+1,Me=await gt(`/api/ca/decks/${i.id}/scenes`,{method:"POST",body:JSON.stringify({orderIndex:q,title:`Slide ${q}`,presetTreeId:null,presetNodeId:null,applyMode:"reinitialize",params:{caption:"",autoplayOnSlideChange:!1}})}),ft=(await se()).resolvedDeck.scenes.find(rt=>rt.scene.id===Me.id);ft&&he(ft),Mt(`Created slide ${q}. Select a CA preset.`)}function Pe(){yt(!1),Ke(q=>Tl(q,X)),ht(q=>q+1)}function Se(q){if(!f?.scenes.length)return;const Me=f.scenes.findIndex(rt=>rt.scene.id===_),De=Math.min(Math.max(Me===-1?0:Me+q,0),f.scenes.length-1),ft=f.scenes[De];ft&&ft.scene.id!==_&&he(ft)}function Be(){if(!st?.scene.preset_tree_id||!st.scene.preset_node_id)return;const q=new URLSearchParams({node:st.scene.preset_node_id,return:`/admin/edit/${a}?scene=${st.scene.id}`});Pi(`/admin/libraries/${st.scene.preset_tree_id}?${q.toString()}`)}function ke(){if(!E||E.kind==="chapter")return;const q=st?`/admin/edit/${a}?scene=${st.scene.id}`:`/admin/edit/${a}`,Me=new URLSearchParams({node:E.id,return:q});Pi(`/admin/libraries/${E.tree_id}?${Me.toString()}`)}return ee.useEffect(()=>{function q(Me){if(!gy(Me.target)){if(Me.key==="ArrowDown"||Me.key==="ArrowRight"){Me.preventDefault(),Se(1);return}if(Me.key==="ArrowUp"||Me.key==="ArrowLeft"){Me.preventDefault(),Se(-1);return}Me.key===" "&&(Me.preventDefault(),yt(De=>!De))}}return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[_,f]),g.jsxs("main",{className:"studio-shell",children:[g.jsxs("header",{className:"topbar",children:[g.jsxs("div",{className:"deck-title-editor",children:[g.jsx("p",{className:"eyebrow",children:"CA Studio Admin"}),g.jsx("input",{"aria-label":"Deck name",className:"deck-title-input",value:l,onChange:q=>c(q.target.value)})]}),g.jsxs("div",{className:"topbar-actions",children:[g.jsx("div",{className:"status",children:St}),g.jsx(za,{})]})]}),g.jsxs("section",{className:"editor-layout",children:[g.jsx(CR,{activeSceneId:_,canDeleteSlide:!!st,sceneCount:W,scenes:f?.scenes??[],onBack:()=>Pi(mo("decks")),onDeleteSlide:()=>{Je()},onEditScene:Le,onReorderSlides:q=>{pt(q)},onSaveNewSlide:()=>{Z()},onSelectScene:he}),T&&st?g.jsx(JR,{assignedNodeId:I??void 0,assignedNodeName:H,autoplayOnSlideChange:xe,caption:ne,scene:st,slideTitle:ge,onAutoplayChange:F,onCaptionChange:ye,onClose:()=>C(!1),onSelectCa:Fe,onSlideTitleChange:K}):null,v?g.jsx(e2,{assignedNodeId:I??void 0,loading:j,nodes:D,presetTrees:m,resolvedNode:A,selectedNode:E,selectedTreeId:B,onClose:()=>x(!1),onEditSelected:ke,onSelectNode:q=>{je(q)},onSelectTree:q=>{ze(q)},onUseSelected:()=>{Qe()}}):null,g.jsxs("section",{className:"panel editor-panel deck-editor-panel",children:[g.jsxs("div",{className:"editor-header",children:[g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Visualization"}),g.jsx("h2",{children:st?ge:H})]}),g.jsxs("div",{className:"button-row",children:[g.jsx(za,{}),g.jsx("button",{"aria-label":"Previous slide",className:"deck-nav-button",disabled:!z,title:"Previous slide",type:"button",onClick:()=>Se(-1),children:"←"}),g.jsxs("span",{className:"deck-position",children:[It>=0?It+1:0,"/",W]}),g.jsx("button",{"aria-label":"Next slide",className:"deck-nav-button",disabled:!Ye,title:"Next slide",type:"button",onClick:()=>Se(1),children:"→"}),g.jsx("button",{disabled:!I,type:"button",onClick:Be,children:"Edit CA"}),g.jsx("button",{disabled:!I,type:"button",onClick:Pe,children:"Step"}),g.jsx("button",{className:"primary playback-button",disabled:!I,type:"button",onClick:()=>yt(q=>!q),children:Et?"⏸":"▶"})]})]}),I?g.jsx(Fu,{caption:st?ne:"",cells:nt,settings:X,onCellsChange:()=>{}}):g.jsx("section",{className:"empty-slide-stage",children:g.jsxs("div",{children:[g.jsx("p",{className:"eyebrow",children:"Empty slide"}),g.jsx("h3",{children:"Select a CA preset"}),g.jsx("p",{children:"This slide has no simulation asset assigned yet."}),g.jsx("button",{className:"primary",type:"button",onClick:Fe,children:"Select CA preset"})]})}),g.jsxs("footer",{className:"metrics",children:[g.jsxs("span",{children:["Generation ",g.jsx("strong",{children:zt})]}),g.jsxs("span",{children:["Live cells ",g.jsx("strong",{children:my(nt)})]}),g.jsxs("span",{children:["Selected node ",g.jsx("strong",{children:$?$.slice(0,8):"none"})]}),g.jsxs("span",{children:["Assigned node ",g.jsx("strong",{children:I?I.slice(0,8):"none"})]})]})]})]})]})}zM.createRoot(document.getElementById("root")).render(g.jsx(ee.StrictMode,{children:g.jsx(kR,{})}));